Search code examples
dartcomparisonequality

What is the default == behavior for Dart objects?


I have the following dart class...

class Color {
  final int value;
  const Color._internal(this.value);

  static const Color WHITE = const Color._internal(0);
  static const Color BLACK = const Color._internal(1);

  int get hashCode => value;
  String toString() => (this == WHITE) ? 'W' : 'B';
}

I have not implemented the == operator.

What will happen when I use the == operator on two instances of these objects?


Solution

  • It will check if the instances reference the same object.

    Color._internal(0) == Color._internal(0); // false
    const Color._internal(0) == const Color._internal(0); // true
    
    final foo = Color._internal(1);
    foo == Color._internal(2); // false
    foo == Color._internal(1); // false
    foo == foo; // true
    

    So it will only be true for the same variable (or when passing that reference) or for const references.

    Object.==

    The default == implementation is Object.== because your Color class inherently subclasses Object (or Object? when null).

    If you take a look at the Object.== implementation), you will see that it is simply:

    external bool operator ==(Object other);
    

    Here is a quick summary of how that behaves: the two objects need to be the exact same object.

    identical

    I am pretty sure that the identical fuction behaves in exactly the same manner, even though the wording in the documentation is a little bit different:

    Check whether two references are to the same object.

    hashCode

    Overriding hashCode has no impact on the default == implementation because it will always use identityHashCode.

    Learn more about Object.hashCode.