Sobes.tech
Junior — Middle

If you create a data class in Kotlin that inherits from another class, will the hashCode and equals methods be automatically overridden or need to be implemented manually?

sobes.tech AI

Answer from AI

In Kotlin, if a data class inherits from another class (not directly from Any), then the automatic generation of equals(), hashCode(), and toString() methods does not occur. This is because the compiler cannot guarantee the correctness of these methods' implementation when inheritance is involved.

Therefore, in such a situation, you will need to manually implement the equals() and hashCode() methods to ensure proper comparison and hashing of objects.

Example:

open class Base(val id: Int)

data class Derived(val name: String, val age: Int) : Base(id = 0) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is Derived) return false
        if (!super.equals(other)) return false

        if (name != other.name) return false
        if (age != other.age) return false

        return true
    }

    override fun hashCode(): Int {
        var result = super.hashCode()
        result = 31 * result + name.hashCode()
        result = 31 * result + age
        return result
    }
}

If a data class does not inherit from any user-defined class (only from Any), then the methods are generated automatically.