44 lines
1.2 KiB
Plaintext

== Why is this an issue?
In Kotlin, you must override either both or neither of the `equals(Any?)` and `hashCode()` methods 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 `equals` comparisons on the object is modified.
- If two objects are equal according to the `equals` method, 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,kotlin]
----
class MyClass { // Noncompliant - should also override "hashCode()"
override fun equals(other: Any?): Boolean {
/* ... */
}
}
----
=== Compliant solution
[source,kotlin]
----
class MyClass { // Compliant
override fun equals(other: Any?): Boolean {
/* ... */
}
override fun hashCode(): Int {
/* ... */
}
}
----
== Resources
* https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/hash-code.html[`hashCode` - kotlinlang.org]