equals
should be overridden correctly KT-E1003When overriding equals()
in Kotlin, it is crucial to ensure that the method has the correct signature, much like it is in Java.
In the Any
class, which is the root of the Kotlin class hierarchy, the equals()
method has the following signature:
fun equals(other: Any?): Boolean
The parameter 'other' is of type Any?
, which means it can accept any object or null
.
When you override the equals()
method in your own class, it is expected to have the same signature.
However, a common mistake is to use a different parameter type.
For example, if you accidentally override equals()
with a different parameter type, like here - fun equals(other: MyType)
, it violates the method signature required by the Any
class.
Using this altered signature causes the method to be overloaded instead of overridden. Because of this, any collection class that may rely on equals()
to perform object identity checks will not function as expected; it will use the default equals()
implementation instead of the more specialized one.
To fix this issue, ensure that the signature of your equals
implementation matches that of Any
, and also add the override
modifier to it, so Kotlin knows you are trying to override Any.equals()
.
class Person(val name: String) {
override fun equals(other: Person): Boolean {
// implementation
}
}
class Person(val name: String) {
override fun equals(other: Any?): Boolean {
// implementation
}
}