rspec/rules/S1206/dart/rule.adoc

42 lines
1.1 KiB
Plaintext
Raw Normal View History

2024-07-10 17:13:20 +02:00
== Why is this an issue?
In Dart, you must override either both or neither of the operator `==` and `hashCode()` method in order 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.
=== Noncompliant code example
[source,dart]
----
2024-07-11 15:00:51 +02:00
class A {
2024-07-10 17:13:20 +02:00
final int value;
2024-07-11 15:00:51 +02:00
A(this.value);
2024-07-10 17:13:20 +02:00
@override
2024-07-11 15:00:51 +02:00
bool operator ==(Object other) => other is A && other.value == value;
2024-07-10 17:13:20 +02:00
}
----
=== Compliant solution
[source,dart]
----
2024-07-11 15:00:51 +02:00
class A {
2024-07-10 17:13:20 +02:00
final int value;
2024-07-11 15:00:51 +02:00
A(this.value);
2024-07-10 17:13:20 +02:00
@override
2024-07-11 15:00:51 +02:00
bool operator ==(Object other) => other is A && other.value == value;
2024-07-10 17:13:20 +02:00
@override
int get hashCode => value.hashCode;
}
----
2024-07-11 15:00:51 +02:00
== Resources
* https://dart.dev/tools/linter-rules/unnecessary_overrides[Dart Lint rule]