从Java访问Kotlin密封类
到目前为止,我一直在使用这个Kotlin密封类:从Java访问Kotlin密封类,java,kotlin,sealed-class,Java,Kotlin,Sealed Class,到目前为止,我一直在使用这个Kotlin密封类: sealed class ScanAction { class Continue: ScanAction() class Stop: ScanAction() ... /* There's more but that's not super important */ } 这在我的Kotlin和Java代码中都非常有效。今天我尝试将该类改为使用对象(建议减少额外的类实例化): 我可以在我的其他Kotlin文件中引用这个easy
sealed class ScanAction {
class Continue: ScanAction()
class Stop: ScanAction()
... /* There's more but that's not super important */
}
这在我的Kotlin和Java代码中都非常有效。今天我尝试将该类改为使用对象(建议减少额外的类实例化):
我可以在我的其他Kotlin文件中引用这个easy peasy,但我现在很难在Java文件中使用它
在尝试在Java中引用时,我尝试了以下以及这两个回退编译错误:
ScanAction test = ScanAction.Continue;
ScanAction test = new ScanAction.Continue();
有人知道我现在如何在Java中引用实例吗?您必须使用
实例
属性:
ScanAction test = ScanAction.Continue.INSTANCE;
啊,谢谢你!这让我发疯。我应该考虑检查哪些属性对我是可用的……在一个100%Kotlin项目中,我试图从XML数据绑定的密封类中传递一个类,这让我发疯了!直到我注意到数据绑定生成的代码是Java。这很快让我找到了你的答案。谢谢在我的例子中,我得到
无法解析符号“INSTANCE”
ScanAction test = ScanAction.Continue.INSTANCE;