Sobes.tech
Junior — Middle

Should the fields of the base class be considered when overriding the equals method in a data class?

sobes.tech AI

Answer from AI

In Kotlin, a data class automatically generates equals, hashCode, and toString methods, considering only the properties declared in the class itself. If your class inherits from a base class with its own fields, these fields are not included in the comparison by default.

If the comparison logic should include the base class fields, you should override the equals method manually, calling super.equals(other) and adding checks for the base class fields. Otherwise, if the base class does not contain data relevant to the comparison, you can rely on the generated method.

Example of overriding equals considering the base class:

open class Base(val id: Int) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is Base) return false
        return id == other.id
    }

    override fun hashCode() = id
}

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

    override fun hashCode() = super.hashCode() * 31 + name.hashCode()
}

Therefore, consider the base class fields in equals if they are important for the object comparison logic.

Should the fields of the base class be considered… - sobes.tech