Sobes.tech
Junior — Middle

What are the reasons why inheritance is not allowed in Data Class in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, data classes are designed for storing data and automatically generate methods like equals(), hashCode(), toString(), as well as functions copy() and components for destructuring. Inheritance from data class is prohibited for several reasons:

  • The complexity of correctly generating methods when inheriting, as a subclass may add new properties, which would break the logic of comparison and copying.
  • Violation of the principle of immutability and predictable behavior of data class.

Therefore, to avoid errors and ambiguities, Kotlin does not allow inheritance of data class.