OK, now that Kotlin is officially out and I am starting to play with it again, I am quite confused that I need to choose between the advantages of sealed
and data
but somehow can't have both.
This, for example, seems to make sense to me, but does not compile:
sealed class Expr {
data class Const(val number: Double) : Expr()
data class Sum(val expr1 : Expr, val expr2 : Expr) : Expr()
}
because the data classes cannot extend other classes.
Is there something I am missing?
Shortly before having entered Beta state, Kotlin team had decided to add certain limitations on data
classes usage (see this post) because of the problems they caused in class hierarchies.
One of the limitations is that data
class should not subtype another class, only interfaces are allowed. Consequently, data
classes cannot derive from a sealed class
.
This was a necessary measure to avoid further postponing the 1.0 release. Some of the limitations were said to be lifted in future releases, once the problematic cases are thoroughly reviewed and a good design solution is found.
来源:https://stackoverflow.com/questions/35921234/kotlin-sealed-class-cannot-contain-data-classes-why