Junior — Middle
Should the hashCode method be overridden in a data class to ensure the correct functioning of collections?
sobes.tech AI
Answer from AI
In Kotlin, a data class automatically generates equals(), hashCode(), and toString() methods based on all properties declared in the primary constructor. This means that manually overriding hashCode() is usually unnecessary, as the generated method already ensures correct behavior with collections that use hashing (e.g., HashSet, HashMap).
However, if you add additional properties outside the constructor or want to change the comparison logic, you may need to override hashCode() and equals() manually to maintain their contract and ensure proper collection behavior.
Example of a data class with automatic hashCode:
data class User(val id: Int, val name: String)
val userSet = hashSetOf(User(1, "Alice"))
println(userSet.contains(User(1, "Alice"))) // true
Here, contains works correctly thanks to the generated methods.