Rules / Correctness / hash-and-equals
hash-and-equals
Require hashCode and == to be overridden together.
Flags a class, mixin, or mixin class that overrides the == operator without
also defining hashCode, or defines hashCode without overriding ==. The
two are bound by a contract: any two objects that compare equal must return
the same hash code. Overriding only one breaks that invariant, so the type
misbehaves as a Map key or Set element — lookups miss and duplicates slip
through. Override both and derive them from the same fields.
Invalid
example.dartdart
class A {
@override bool operator ==(Object other) => identical(this, other);
}
class B {
@override int get hashCode => 42;
}
class C {
@override final int hashCode = 7;
}
mixin M {
@override bool operator ==(Object other) => true;
}
class D {
final int value = 0;
@override bool operator ==(Object other) => other is D;
}
Override 'hashCode' if you override the '==' operator.
1class A {
2 @override bool operator ==(Object other) => identical(this, other);
∙
Override the '==' operator if you override 'hashCode'.
5class B {
6 @override int get hashCode => 42;
∙
Override the '==' operator if you override 'hashCode'.
9class C {
10 @override final int hashCode = 7;
∙
Override 'hashCode' if you override the '==' operator.
13mixin M {
14 @override bool operator ==(Object other) => true;
∙
Override 'hashCode' if you override the '==' operator.
18 final int value = 0;
19 @override bool operator ==(Object other) => other is D;
∙
Valid
example.dartdart
class A {
@override
bool operator ==(Object other) => identical(this, other);
@override
int get hashCode => 0;
}
class B {
void method() {}
}
mixin M {
@override
bool operator ==(Object other) => true;
@override
int get hashCode => 1;
}
class C {
final int value = 0;
int get other => 0;
}
enum E { a, b }
How to configure
Set the severity of hash-and-equals in your falcon.json:
falcon.jsonjson
{
"linter": {
"rules": {
"correctness": {
"hash-and-equals": "error"
}
}
}
}