37

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 ?

Argenti Apparatus
  • 3,507
  • 2
  • 24
  • 33

4 Answers4

52

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
}
Erik Campobadal
  • 725
  • 6
  • 13
Christophe Herreman
  • 15,649
  • 7
  • 57
  • 86
  • 3
    if you override `operator ==` you will also need to override `hashCode`. See this answer [here](https://stackoverflow.com/a/22999113/9449426) for how to do this – NearHuscarl Dec 02 '19 at 06:14
  • 1
    What if i want to check If a list of model already contains a particular object ? – minato Jan 07 '20 at 11:21
6

You can use identical(this, other).

Alexandre Ardhuin
  • 62,400
  • 12
  • 142
  • 126
2

For completeness, this is a supplemental answer to the existing answers.

If some class Foo does not override ==, then the default implementation is to return whether they are the same object. The documentation states:

The default behavior for all Objects is to return true if and only if this object and other are the same object.

Suragch
  • 428,106
  • 278
  • 1,284
  • 1,317
0

On a different yet similar note, in cases where the framework calls to check the equality among the objects e.g. in case of list.toSet() to get the unique elements from a list, identical(this, other) may not be a choice. That time the class must override the == operator and the hasCode() methods.

However for this case another way could be to use the equatable package. This saves a lot of boiler plate code and is especially handy when you have lot of model classes.

Sisir
  • 3,665
  • 4
  • 21
  • 30