13

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?

hotkey
  • 140,743
  • 39
  • 371
  • 326
david.mihola
  • 12,062
  • 8
  • 49
  • 73
  • Since Kotlin 1.1 this is now possible https://kotlinlang.org/docs/reference/whatsnew11.html?q=da&p=0#sealed-and-data-classes. – Stim Aug 09 '17 at 07:50

1 Answers1

16

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.

hotkey
  • 140,743
  • 39
  • 371
  • 326
  • 1
    Thanks for the link! – Lovis Mar 10 '16 at 16:23
  • So, maybe there's hope - thanks for the explanation! – david.mihola Mar 11 '16 at 08:03
  • 1
    If I am reading right, it looks like this restriction will be lifted with 1.1 (see [this issue](https://github.com/Kotlin/KEEP/issues/31) and [this design document](https://github.com/Kotlin/KEEP/blob/master/proposals/data-class-inheritance.md)). – mkobit Dec 02 '16 at 14:37
  • 1
    @mkobit, correct, this is planned for, 1.1. However, any of the features which are worked on for the 1.1 release can still be changed, no compatibility guarantees are provided for the preview builds. – hotkey Dec 02 '16 at 14:48
  • 4
    This has been fixed and is now possible. – Jeff Padgett Feb 28 '20 at 17:42