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?
They cannot be abstract, open, sealed or inner. They can only inherit from other non-data classes (eg. sealed classes after 1.1, before 1.1 data classes can only implement interfaces). Data classes can override properties and methods from the interfaces they implement.
In layman terms, as the name suggests, sealed classes are sealed or closed, hence making them restricted. Sealed classes are used for representing restricted class hierarchies wherein the object or the value can have value only among one of the types, thus fixing your type hierarchies.
Kotlin has a great feature called sealed class, which allow us to extend an abstract class in a set of fixed concrete types defined in the same compilation unit (a file). In other words, is not possible to inherit from the abstract class without touching the file where it is defined.
To define a sealed class, just precede the class modifier with the sealed keyword. The sealed classes also have one another distinct feature, their constructors are protected by default. A sealed class is implicitly abstract and hence it cannot be instantiated.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With