45 lines
1.2 KiB
Plaintext
45 lines
1.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
In data classes, the default behavior of the `equals()` method is to check the equality by field values. This works well for primitive fields or fields, whose type overrides `equals()`, but this behavior doesn't work as expected for array fields.
|
|
|
|
|
|
By default, array fields are compared by their reference, so overriding `equals()` is highly recommended to ensure a deep equality check. The same applies to the `hashcode()` method.
|
|
|
|
|
|
This rule reports an issue if a record class has an array field and is not overriding `equals()` or `hashcode()` methods.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,kotlin]
|
|
----
|
|
data class Person(val names: Array<String>, val age: Int) {} // Noncompliant
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,kotlin]
|
|
----
|
|
data class Person(val names: Array<String>, val age: Int) {
|
|
override fun equals(other: Any?): Boolean {
|
|
if (this === other) return true
|
|
if (javaClass != other?.javaClass) return false
|
|
|
|
other as Person
|
|
|
|
if (!names.contentEquals(other.names)) return false
|
|
if (age != other.age) return false
|
|
|
|
return true
|
|
}
|
|
|
|
override fun hashCode(): Int {
|
|
var result = names.contentHashCode()
|
|
result = 31 * result + age
|
|
return result
|
|
}
|
|
}
|
|
----
|
|
|