Skip to content

Files

Latest commit

 

History

History
40 lines (30 loc) · 944 Bytes

hash_and_equals.md

File metadata and controls

40 lines (30 loc) · 944 Bytes

Pattern: Missing override for == or hashCode

Issue: -

Description

Every object in Dart has a hashCode. Both the == operator and the hashCode property of objects must be consistent in order for a common hash map implementation to function properly. Thus, when overriding ==, the hashCode should also be overridden to maintain consistency. Similarly, if hashCode is overridden, == should be also.

Example of incorrect code:

class Bad {
 final int value;
 Bad(this.value);

 @override
 bool operator ==(Object other) => other is Bad && other.value == value;
}

Example of correct code:

class Better {
 final int value;
 Better(this.value);

 @override
 bool operator ==(Object other) => other is Better && other.value == value;

 @override
 int get hashCode => value.hashCode;
}

Further Reading