In Dart, you must override either both or neither of the operator ==
and the hashCode()
method.
That is required to keep the contract between the two:
- whenever the
hashCode
method is invoked on the same object more than once, it must consistently return the same integer, provided
no information used in ==
comparisons on the object is modified
- if two objects are equal according to the
==
operator, then calling the hashCode
method on each of the two objects
must produce the same integer result
By overriding only one of the two methods with a non-trivial implementation, this contract is almost certainly broken.
Exceptions
The rule does not raise in mixins, because they are not supposed to be instantiated directly, but rather included in other classes.
The rule raises, however, on mixin classes, since they can also be used as normal classes, and instantiated directly.
Noncompliant code example
class A {
final int value;
A(this.value);
@override
bool operator ==(Object other) => other is A && other.value == value;
}
Compliant solution
class A {
final int value;
A(this.value);
@override
bool operator ==(Object other) => other is A && other.value == value;
@override
int get hashCode => value.hashCode;
}