Kotlin中另一个类内的密封类无法编译:无法访问'< init>'它是私人的 [英] Sealed classes inside another class in Kotlin can't be compiled: cannot access '<init>' it is private
问题描述
如果我使用了 docs
class SomeActivity : AppCompatActivity() {
sealed class Expr
data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()
}
它无法编译,并显示错误:
it does not compile, with the error:
Cannot access '<init>', it is private in 'Expr'.
但是,将其移到封闭类之外会使它编译:
However, moving it outside the enclosing class makes it compile:
sealed class Expr
data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()
class SomeActivity : AppCompatActivity() {
}
为什么会这样?这是预期的行为吗?文档似乎没有提到这一点.
Why is this so? Is this an intended behavior? The docs does not seem to mention this.
推荐答案
是的,事实证明这是预期的行为.根据允许非嵌套子类的建议 :
Yes, it turns out to be intended behavior. According to the proposal allowing non-nested subclasses:
建议:在同一文件中允许顶级子类用于顶级密封类.
对于非顶级密封类,应在其内部声明所有子类.因此,对于这些类,没有任何变化.
For a non top-level sealed class all subclasses should be declared inside it. So, for such classes nothing changes.
您想要的方案被列为一个悬而未决的问题.在 https://youtrack.jetbrains.com/issue/KT-13495 .目前似乎没有人对此进行研究.在讨论该提案时,开发人员说:
The scenario you want is listed as an open question. There is a ticket for it at https://youtrack.jetbrains.com/issue/KT-13495. Nobody seems to be working on it at the moment. In the discussion of the proposal, the developer says:
Well, there is some not-trivial implementations details(about generation synthetic constructors) which was solved for top-level classes but how do it in general is not clear.
这篇关于Kotlin中另一个类内的密封类无法编译:无法访问'< init>'它是私人的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!