Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two objects to see if they are the same instance, in Dart?

Tags:

dart

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 ?

like image 345
Argenti Apparatus Avatar asked Aug 25 '13 11:08

Argenti Apparatus


People also ask

How do you check whether two objects are of the same instance?

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.

What is == in Dart?

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.

How do you compare two classes in flutter?

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.


2 Answers

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 } 
like image 151
Christophe Herreman Avatar answered Sep 21 '22 16:09

Christophe Herreman


You can use identical(this, other).

like image 36
Alexandre Ardhuin Avatar answered Sep 17 '22 16:09

Alexandre Ardhuin