Christian
Christian

Reputation: 1068

How exactly does the == operator work in dart when comparing objects?

So the Dart API says this about the == operator:

The equality operator.

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

Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:

Total: It must return a boolean for all arguments. It should never throw.

Reflexive: For all objects o, o == o must be true.

Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.

Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must be true.

The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.

If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.

But how exactly does Dart check, if 2 Objects are the same?

return true if and only if this object and other are the same object

could be understood as "checks if both objects are references to the same instance" which apparently isn't the case.

So lets say I have 2 instances of

class Car {
  int tires = 4;
  Color color = Colors.blue;
  int doors = 4;
}

Car carA = Car();
Car carB = Car();

From my understanding if I check carA == carB, Dart compares all properties of both instances by looping over them?

If thats the case, does it always drill down to primitives if, for example, some properties are non-primitive classes?

Thanks

Upvotes: 3

Views: 2330

Answers (1)

Patrick O'Hara
Patrick O'Hara

Reputation: 2229

I believe that Dart does "checks if both objects are references to the same instance". If you want to compare the properties you can override the == operator, for example:

class Car {
  int tires = 4;
  int doors = 4;

  @override
   bool operator ==(Object other) {
     return other is Car && this.tires == other.tires && this.doors == other.doors;
   } 
  @override
  int get hashCode => this.tires * this.doors;
}

void main() {
  Car carA = Car();
  Car carB = Car();
  print("equal ${carA==carB}");
  print("identical ${identical(carA,carB)}");
}

Now the cars are equal. Note that the function identical() does check for the same object.

The Dart Spec specifies that constant objects do check the properties, for example:

class ConstCar {
  final int tires = 4;
  final int doors = 4;
  const ConstCar();
}

void main() {
  ConstCar constCarA = const ConstCar();
  ConstCar constCarB = const ConstCar();
  print("equal ${constCarA==constCarB}");
  print("identical ${identical(constCarA,constCarB)}");
}

This returns true for == and identical().

Upvotes: 4

Related Questions