Sobes.tech
Junior — Middle

How is the hashCode method calculated in a data class?

sobes.tech AI

Answer from AI

In Kotlin, a data class automatically generates a hashCode() method, which is computed based on all properties declared in the primary constructor of the class.

The algorithm is roughly as follows:

  • For each property, its own hashCode() is called.
  • These hash codes are combined using a specific formula (usually involving multiplication by a prime number and addition) to produce the final hash code of the object.

This ensures that two data class objects with the same property values will have the same hashCode(), which is important for correct operation in collections such as HashSet or HashMap.

Example:

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

val user1 = User(1, "Alice")
val user2 = User(1, "Alice")

println(user1.hashCode() == user2.hashCode()) // true
How is the hashCode method calculated in a data… - sobes.tech