Sobes.tech
Junior — Middle

Why override the hashCode method for universal objects in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, the hashCode method is overridden for universal objects to ensure correct behavior with hash-based data structures like HashMap or HashSet. By default, hashCode may be based on the object's memory address, which is not suitable if logically equal objects should have the same hash.

Overriding hashCode together with equals guarantees that objects considered equal will have the same hash code, which is important for correct lookup, insertion, and deletion in collections.

Example of overriding in a data class (Kotlin automatically generates equals and hashCode):

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

If the class is not a data class, you need to override manually:

override fun equals(other: Any?): Boolean {
    if (this === other) return true
    if (other !is User) return false
    return id == other.id && name == other.name
}

override fun hashCode(): Int {
    return 31 * id + name.hashCode()
}