I have a class:
open data class Person(var name: String)
and another class:
data class Student(var reg: String) : Person("")
this gives me an error that:
error: modifier 'open' is incompatible with 'data'
if I remove data from Person
class it's fine.
why kotlin open and data incompatible?
From https://kotlinlang.org/docs/reference/data-classes.html:
So the main point is that data class has some generated code (
equals
,hashCode
,copy
,toString
,componentN
functions). And such code must not be broken by the programmer. As a result, data class has some restrictions.As the documentation states,
The reason that they can not be inherited from is that inheriting from a data class causes problems/ambiguity with how their generated methods (
equals
,hashcode
, etc.) should work. See further discussion about this here.Since Kotlin 1.1, the restrictions on data classes have been lifted slightly: they can now inherit from other classes, as described in detail in the related proposal. However, they still can not inherit from classes themselves.
Note that data classes "only" provide the extra convenience of the automatic
equals
,hashcode
,toString
,component
, andcopy
functions. If you don't need those, then a class like the following still has properties with getters/setters and a constructor in a very brief form, and has no limitations on how you can use it with inheritance: