Say I have a class that has many instance variables,. I want to overload the == operator (and hashCode) so I can use instances as keys in maps.
class Foo { int a; int b; SomeClass c; SomeOtherClass d; // etc. bool operator==(Foo other) { // Long calculation involving a, b, c, d etc. } }
The comparison calculation may be expensive, so I want to check if other
is the same instance as this
before making that calculation.
How do I invoke the == operator provided by the Object class to do this ?
If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal.
Dart supports == for equality and identical(a, b) for identity. Dart no longer supports the === syntax. Use == for equality when you want to check if too objects are "equal". You can implement the == method in your class to define what equality means.
In this example, we are using the equality operator (==) to compare 2 student objects. But we didn't override that equality operator in our Student class, therefore the program will use the default equality operator defined in the Object class. If we look at the document, it says: /** * The equality operator.
You're looking for "identical", which will check if 2 instances are the same.
identical(this, other);
A more detailed example?
class Person { String ssn; String name; Person(this.ssn, this.name); // Define that two persons are equal if their SSNs are equal bool operator ==(Person other) { return (other.ssn == ssn); } } main() { var bob = new Person('111', 'Bob'); var robert = new Person('111', 'Robert'); print(bob == robert); // true print(identical(bob, robert)); // false, because these are two different instances }
You can use identical(this, other)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With