Kotlin: sealed class cannot “contain” data classes? Why?

被刻印的时光 ゝ 提交于 2020-01-11 08:19:08

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!