Junior — Middle
Is it possible to create inheritance using data class in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, data class by default cannot be open for inheritance because they are declared with the final modifier. This is done to preserve semantics and automatic generation of methods such as equals(), hashCode(), toString(), as well as copy().
However, starting with Kotlin 1.1, you can explicitly make a data class open for inheritance by adding the open modifier:
open data class User(val name: String, val age: Int)
class Employee(name: String, age: Int, val position: String) : User(name, age)
But keep in mind that inheriting from a data class is a rare practice and can lead to unexpected results, as the copy() and componentN() methods do not consider subclass properties. Therefore, it is usually recommended to use composition instead of inheritance with data class.