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

前端 未结 2 1099
一生所求
一生所求 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:24

    Basically, == is equality operator and "is" is the instanceof operator of Dart (If you come from Java background, if not, it basically tells you if something is of type something).

    Use == for equality, when you want to check if two objects are equal. You can implement the == operator (method) in your class to define on what basis do you want to judge if two objects are equal.

    Take this example:

    class Car {
        String model;
        String brand;
        Car(this.model, this.brand);
    
        bool operator == (otherObj) {
            return (otherObj is Car && other.brand == brand); //or however you want to check
            //On the above line, we use "is" to check if otherObj is of type Car
        }
    }
    

    Now you can check if two cars are "equal" based on the condition that you have defined.

    void main() {
      final Car micra = Car("Micra", "Nissan");
      print(micra == Car("Micra", "Nissan")); // true
      print(micra is Car("Micra", "Nissan")); // true
    }
    

    Hence, == is something you use to decide if two objects are equal, you can override and set it as per your expectations on how two objects should be considered equal.

    On the other hand, "is" basically tells you if an instance is of type object (micra is of type Car here).

提交回复
热议问题