Sobes.tech
Junior — Middle

Is the field declared inside a data class used in the hashCode method?

sobes.tech AI

Answer from AI

In Kotlin, for data class, the compiler automatically generates hashCode(), equals(), toString(), as well as copy() and destructuring components. The hashCode() method is based on all properties declared in the primary constructor of the data class (i.e., those specified after the class name).

If an additional field is declared inside the data class outside the primary constructor, it does not participate in the calculation of hashCode() and equals(). This is because these methods consider only the properties declared in the constructor to ensure correct comparison and hashing of objects based on the main data.

Example:

data class User(val id: Int, val name: String) {
    var age: Int = 0 // does not participate in hashCode and equals
}

fun main() {
    val user1 = User(1, "Alice")
    val user2 = User(1, "Alice")
    user1.age = 25
    user2.age = 30
    println(user1 == user2) // true, because age is not considered
    println(user1.hashCode() == user2.hashCode()) // true
}
Is the field declared inside a data class used in the… - sobes.tech