Junior — Middle
Is it possible to determine inheritance between a data class and another class?
sobes.tech AI
Answer from AI
In Kotlin, a data class (data class) can inherit from another class if it is not final (i.e., open for inheritance). However, a data class automatically inherits from Any and must have at least one parameter in its constructor.
Important:
- A data class cannot be
openorabstract. - Inheritance from a data class is possible, but a data class itself cannot be a parent (i.e., you cannot inherit from a data class).
Example:
open class Person(val name: String)
data class Employee(val id: Int, val person: Person) : Person(person.name)
Thus, inheritance between a data class and another class is possible but with restrictions, and composition (embedding objects) is often used instead of inheritance for data classes.