Reputation: 1068
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 betrue
.Symmetric: For all objects
o1
ando2
,o1 == o2
ando2 == o1
must either both betrue
, or both befalse
.Transitive: For all objects
o1
,o2
, ando3
, ifo1 == o2
ando2 == o3
aretrue
, theno1 == o3
must betrue
.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
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