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 classcannot be open (open), meaning it cannot be inherited directly. - The compiler automatically generates
equals(),hashCode(),toString(), as well ascopy()and destructuring functions, which complicates proper inheritance. - If you need to extend functionality, you usually create a regular class that contains a
data classas 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.