Sobes.tech
Junior — Middle

What restrictions exist when inheriting from a data class in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, a data class has several restrictions regarding inheritance:

  • A data class cannot be open (open), meaning it cannot be inherited directly.
  • The compiler automatically generates equals(), hashCode(), toString(), as well as copy() and destructuring functions, which complicates proper inheritance.
  • If you need to extend functionality, you usually create a regular class that contains a data class as a field, or use composition.

Therefore, inheritance from a data class in Kotlin is not supported, and this is done to preserve the semantics and correctness of the automatically generated code.