Sobes.tech
Junior — Middle

Can you define a field in a data class that is excluded from hashCode calculation?

sobes.tech AI

Answer from AI

In Kotlin, properties declared with the hashCode() method are automatically included in the calculation of equals(), hashCode(), and toString() methods if they are part of the primary constructor.

To exclude a field from the hashCode() calculation, you can declare it outside the primary constructor, for example, as a var or val inside the class body. Such properties are not considered in the automatically generated methods.

Example:

data class User(val id: Int, val name: String) {
    var tempData: String = "" // not included in hashCode and equals
}

Here, tempData does not affect hashCode() and equals() because it is not part of the primary constructor.

If you need more fine-grained control, you can override hashCode() and equals() manually.

Can you define a field in a data class that is… - sobes.tech