简体   繁体   English

从Java访问Kotlin密封类

[英]Accessing Kotlin Sealed Class from Java

Up until now I have been using this Kotlin sealed class: 到目前为止,我一直在使用这个Kotlin密封类:

sealed class ScanAction {
   class Continue: ScanAction()
   class Stop: ScanAction()
   ... /* There's more but that's not super important */
}

Which has been working great in both my Kotlin and Java code. 我的Kotlin和Java代码都很好用。 Today I tried changing this class to use objects instead (as is recommended to reduce extra class instantiation): 今天我尝试改变这个类来改为使用对象(建议减少额外的类实例化):

sealed class ScanAction {
   object Continue: ScanAction()
   object Stop: ScanAction()
}

I am able to reference this easy peasy in my other Kotlin files, but I am now struggling to use it in my Java files. 我可以在我的其他Kotlin文件中引用这个简单的peasy,但我现在正努力在我的Java文件中使用它。

I have tried the following and both of these kick back compilation errors when trying to make reference to in Java: 我尝试了以下内容,当尝试在Java中引用时,这些都会导致编译错误:

ScanAction test = ScanAction.Continue;

ScanAction test = new ScanAction.Continue();

Does anyone know how I can reference the instance in Java now? 有谁知道我现在如何用Java引用实例?

您必须使用INSTANCE属性:

ScanAction test = ScanAction.Continue.INSTANCE;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM