Sobes.tech
Junior — Middle

Is it possible to override the hashCode method in a data class?

sobes.tech AI

Answer from AI

Yes, in a Kotlin data class, you can override the hashCode() method. By default, the compiler generates an implementation of hashCode() (and equals()) based on all properties declared in the class constructor.

If you need to change the logic for calculating the hash code, you can explicitly override the method:

data class User(val id: Int, val name: String) {
    override fun hashCode(): Int {
        // For example, use only id for the hash code
        return id.hashCode()
    }
}

However, be cautious: overriding hashCode() should be consistent with equals() to avoid violating the contracts of these methods.

Is it possible to override the hashCode method in a… - sobes.tech