Reputation: 120569
Does Dart support == and === ? What is the difference between equality and identity?
Upvotes: 33
Views: 23300
Reputation: 120569
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 two objects are "equal". You can implement the ==
method in your class to define what equality means. For 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 ==(other) {
return (other is Person && other.ssn == ssn);
}
}
main() {
var bob = Person('111', 'Bob');
var robert = Person('111', 'Robert');
print(bob == robert); // true
print(identical(bob, robert)); // false, because these are two different instances
}
Note that the semantics of a == b
are:
a
or b
are null
, return identical(a, b)
a.==(b)
Use identical(a, b)
to check if two variables reference the same instance. The identical function is a top-level function found in dart:core
.
Upvotes: 59
Reputation: 43128
It should be noted that the use of the identical
function in dart has some caveats as mentioned by this github issue comment:
The specification has been updated to treat identical between doubles like this:
The identical() function is the predefined dart function that returns true iff its two arguments are either:
- The same object.
- Of type int and have the same numeric value.
- Of type double, are not NaNs, and have the same numeric value.
What this entails is that even though everything in dart is an object, and f
and g
are different objects, the following prints true
.
int f = 99;
int g = 99;
print(identical(f, g));
because ints are identical by their value, not reference.
So to answer your question, ==
is used to identify if two objects have the same value, but the identical
is used to test for referential equality except in the case of double
and int
as identified by the excerpt above.
See: equality-and-relational-operators
Upvotes: 5
Reputation: 3564
It should be noted that in Dart, identical
works similarly to Javascript, where (5.0 == 5)
is true
, but identical(5.0, 5)
is false
.
Upvotes: 3
Reputation: 20027
As DART is said to be related to javascript, where the === exists, I wish not be downvoted very quickly.
Identity as a concept means that 1 equals 1, but 1.0 doesn't equal 1, nor does false equal 0, nor does "2" equal 2, even though each one evaluates to each other and 1==1.0 returns true.
Upvotes: 4