Junior — Middle
Is it possible to declare a subclass of a data class in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, a data class cannot be inherited by default because they are automatically declared as final. This is done to ensure the correct operation of generated methods such as equals(), hashCode(), and copy().
If you try to declare a class inheriting from a data class, the compiler will produce an error.
However, if necessary, you can make a data class open by adding the open modifier, but this is not recommended and not directly supported, as data classes cannot be open.
An example that will not compile:
data class User(val name: String)
class AdminUser(val adminLevel: Int) : User("Admin") // Error
Thus, inheritance from a data class in Kotlin is impossible.