rspec/rules/S6207/kotlin/rule.adoc

41 lines
1.2 KiB
Plaintext
Raw Normal View History

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
2022-02-04 17:28:24 +01:00
[source,kotlin]
----
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
2022-02-04 17:28:24 +01:00
[source,kotlin]
----
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
}
----
== See
* https://kotlinlang.org/docs/data-classes.html[Data classes (Kotlin documentation)]