Sobes.tech
Junior — Middle

Is it possible to create subclasses of data classes in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, data class are final by default, meaning they cannot be inherited. This is done to preserve semantics and ensure the correct operation of automatically generated methods such as equals(), hashCode(), and copy().

If you try to create a subclass of a data class, the compiler will produce an error. However, if necessary, you can make a class open (open), but then it cannot be a data class.

An example that will not compile:

data class User(val name: String)

class SpecialUser(val id: Int) : User("default") // Error: cannot inherit from data class

Thus, creating subclasses of data class is not allowed.