0

From Dart Sdk 2.12 the Object type should exclude null, yet operator ==(Object other) accepts null. (for the signature, see sdk source code of object.dart)

Another apparent inconsistency is that it is allowed to declare a reference with both a dynamic and a dynamic? type, while in both cases a nullable object is allowed. There's a difference ?

I asked these two questions together because the signature of == might raise the question that with Object, as with dynamic, the suffix ? is redundant, but in reality from the doc (e.g. understanding null safety) it is clear that this is not true.

Mabsten
  • 1,570
  • 11
  • 16

1 Answers1

2

From the Dart language tour:

To test whether two objects x and y represent the same thing, use the == operator. (In the rare case where you need to know whether two objects are the exact same object, use the identical() function instead.) Here’s how the == operator works:

  1. If x or y is null, return true if both are null, and false if only one is null.
  2. Return the result of the method invocation x.==(y). (That’s right, operators such as == are methods that are invoked on their first operand. For details, see Operators.)

https://dart.dev/guides/language/language-tour#equality-and-relational-operators

So the reason why operator ==(Object other) does not take null is because it is built into the language itself that comparing against null should always be false unless we compare with null. So you get this part of the comparison for "free", so you don't need to think about null input when you are writing your own == operator.

About dynamic vs dynamic?. As far as I know, they both represent the same so dynamic? is just meaningless. You can also see the analyzer and runtime will call it dynamic even if we check the signature of a method declared to return dynamic?:

void main() {
  print(test.runtimeType); // () => dynamic
}

dynamic? test() { }
julemand101
  • 28,470
  • 5
  • 52
  • 48
  • Great. Unfortunately the method doc does not provide the information you reported from the language-tour, and it is not a intuitive mechanism (I don't think there are other methods with a similar non-direct invocation mechanism), at least for me that are used to Kotlin, where using `==` is equivalent to invoking `equals()` directly. In fact I have seen sometimes implement == with a preliminary null check (as an optimization, I guess, before comparing the runtimeTypes), which is actually useless. However now it is clear to me, as you said it allows to get that part of the comparison "for free" – Mabsten May 05 '21 at 13:23
  • 1
    @Mabsten I also don't think it is documented that well. I knew how it works from experience but could not remember where it was defined. But after some searching I found the clearest answer in the language guide. I am sure it is also part of the Dart language specification but it was not that easy to find a short precise paragraph here. – julemand101 May 05 '21 at 13:29