Sobes.tech
Junior — Middle

Is it possible to create inheritable data classes from other classes in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, data classes are final by default, meaning they cannot be inherited. If you try to make a data class inheritable, the compiler will produce an error.

However, starting from Kotlin 1.1, you can declare a data class as open to allow inheritance, but this is not recommended and has limitations. Specifically, an inheritable data class cannot itself be a data class.

Example:

open data class User(val name: String, val age: Int)

class Employee(name: String, age: Int, val position: String) : User(name, age)

But most often, data classes are used specifically for storing data and do not imply inheritance. If a hierarchy is needed, it's better to use regular classes or interfaces.