Junior — Middle
Is inheritance allowed in data classes in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, a data class cannot be inherited by default because they are declared with the final modifier. This is done to preserve the semantics and behavior of the automatically generated methods (equals(), hashCode(), toString(), copy()).
If you try to inherit from a data class, the compiler will give an error.
However, if necessary, you can declare a class as open, but then it cannot be a data class.
Example:
// Compilation error
// data class User(val name: String)
// class AdminUser(name: String) : User(name) // cannot inherit from data class
// Correct
open class User(val name: String)
class AdminUser(name: String) : User(name)
In summary: inheritance from a data class is prohibited.