Data classes have autogenerated implementations of equals
, hashcode
, toString
, copy
and
componentN
. Although the former three methods can still be overridden, there is no use to do so if no special logic is required. The
latter two methods cannot be overridden and cause a compile-time error if attempted.
This rule reports an issue on simple equals
and hashCode
implementations with no additional logic beyond the default
behaviour.
Noncompliant code example
data class Person(val name: String, val age: Int) {
override fun equals(other: Any?): Boolean { // Noncompliant
return other is Person && other.name == name && other.age == age
}
override fun hashCode() = Objects.hash(name, age) // Noncompliant
}
Compliant solution
data class Person(String name, int age) // Compliant
data class Person(val name: String, val age: Int) {
override fun equals(other: Any?): Boolean { // Compliant
return other is Person && other.name.lowercase() == name.lowercase() && other.age == age
}
override fun hashCode() = Objects.hash(name.lowercase(), age) // Compliant
}