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

前端 未结 2 1069
一生所求
一生所求 2021-01-15 16:40

Let\'s say I have:

class Test {
  void method() {
    if (T is int) {
      // T is int
    } 

    if (T == int) {
      // T is int
    }
  }
}
         


        
2条回答
  •  旧巷少年郎
    2021-01-15 17:25

    • identical(x, y) checks if x is the same object as y.

    • x == y checks whether x should be considered equal to y. The default implementation for operator == is the same as identical(), but operator == can be overridden to do deep equality checks (or in theory could be pathological and be implemented to do anything).

    • x is T checks whether x has type T. x is an object instance.

    class MyClass {
      MyClass(this.x);
    
      int x;
    
      @override
      bool operator==(dynamic other) {
        return runtimeType == other.runtimeType && x == other.x;
      }
    
      @override
      int get hashCode => x.hashCode;
    }
    
    void main() {
      var c1 = MyClass(42);
      var c2 = MyClass(42);
      var sameC = c1;
    
      print(identical(c1, c2));    // Prints: false
      print(identical(c1, sameC)); // Prints: true
    
      print(c1 == c2);    // Prints: true
      print(c1 == sameC); // Prints: true
    
      print(c1 is MyClass);      // Prints: true
      print(c1 is c1);           // Illegal.  The right-hand-side must be a type.
      print(MyClass is MyClass); // Prints: false
    }
    

    Note the last case: MyClass is MyClass is false because the left-hand-side is a type, not an instance of MyClass. (MyClass is Type would be true, however.)

    In your code, T is int is incorrect because both sides are types. You do want T == int in that case.

提交回复
热议问题