Sobes.tech
Junior — Middle

Why is inheritance from data class prohibited in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, inheritance from data class is prohibited because data class automatically generates methods like equals(), hashCode(), toString(), as well as copy() and components for destructuring. Allowing inheritance could lead to ambiguities and errors in the behavior of these methods, as subclasses might change the state or logic, violating the contract established by data class.

Therefore, the prohibition of inheritance ensures the integrity and predictability of data class behavior.

Example:

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

// class AdminUser(name: String, age: Int, val adminLevel: Int) : User(name, age) // Compilation error