Sobes.tech
Junior — Middle

How is the hashCode method implemented in a data class?

sobes.tech AI

Answer from AI

In Kotlin, a data class automatically generates a hashCode() method, which computes the hash code based on all properties declared in the primary constructor. This means that if you have a data class with multiple fields, hashCode() will consider the values of all these fields, ensuring correct behavior when using objects in hash-based collections (e.g., HashSet or HashMap).

Example:

data class User(val id: Int, val name: String)

// hashCode() will be automatically computed based on id and name

If needed, you can override hashCode() manually, but usually this is not necessary, as the generated method takes into account all properties affecting object equality.