Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: sealed class cannot "contain" data classes? Why?

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?

like image 574
david.mihola Avatar asked Mar 10 '16 15:03

david.mihola


People also ask

Why data classes Cannot be abstract open sealed or inner?

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.

What is the purpose of sealed class Kotlin?

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.

Can a sealed class inherit from another class Kotlin?

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.

How do you use sealed classes in Kotlin?

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.


1 Answers

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.

like image 83
hotkey Avatar answered Oct 09 '22 07:10

hotkey