Kotlin:密闭类不能“包含"或删除.数据类?为什么? [英] Kotlin: sealed class cannot "contain" data classes? Why?

查看:74
本文介绍了Kotlin:密闭类不能“包含"或删除.数据类?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,现在Kotlin正式退出了市场,我又开始使用它了,我很困惑,我需要在sealeddata的优点之间进行选择,但又不能兼得. /p>

例如,这对我来说似乎很有意义,但无法编译:

sealed class Expr {
    data class Const(val number: Double) : Expr()
    data class Sum(val expr1 : Expr, val expr2 : Expr) : Expr()
}

因为数据类无法扩展其他类.

有什么我想念的吗?

解决方案

在进入Beta状态之前,Kotlin团队决定对data类的使用添加某些限制( 解决方案

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.

这篇关于Kotlin:密闭类不能“包含"或删除.数据类?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆