简体   繁体   中英

What is the difference between == and === in Dart?

Does Dart support == and ===? What is the difference between equality and identity?

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. 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:

  • If either a or b are null , return identical(a, b)
  • Otherwise, return a.==(b)

Use identical(a, b) to check if two variables reference the same instance. identical is a top-level function found in dart:core .

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM