Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Kotlin Sealed Class from Java

Up until now I have been using this Kotlin sealed class:

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. 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.

I have tried the following and both of these kick back compilation errors when trying to make reference to in Java:

ScanAction test = ScanAction.Continue;

ScanAction test = new ScanAction.Continue();

Does anyone know how I can reference the instance in Java now?

like image 270
ssawchenko Avatar asked Dec 13 '18 23:12

ssawchenko


People also ask

Can I use Kotlin data class in Java?

As a quick refresher, Kotlin is a modern, statically typed language that compiles down for use on the JVM. It's often used wherever you'd reach for Java, including Android apps and backend servers (using Java Spring or Kotlin's own Ktor).

How do I call a sealed class at Kotlin?

Sealed class is a class which restricts the class hierarchy. A class can be declared as sealed class using "sealed" keyword before the class name. It is used to represent restricted class hierarchy. Sealed class is used when the object have one of the types from limited set, but cannot have any other type.

Can we inherit sealed class in Kotlin?

One of the advantages of sealed interfaces over sealed classes is the ability to inherit from multiple sealed interfaces. This is impossible for sealed classes because of the lack of multiple inheritance in Kotlin.

Can Kotlin interact with Java?

Kotlin provides the first-class interoperability with Java, and modern IDEs make it even better. In this tutorial, you'll learn how to use both Kotlin and Java sources in the same project in IntelliJ IDEA. To learn how to start a new Kotlin project in IntelliJ IDEA, see Getting started with IntelliJ IDEA.


1 Answers

You have to use the INSTANCE property:

ScanAction test = ScanAction.Continue.INSTANCE;
like image 73
Francesc Avatar answered Oct 04 '22 14:10

Francesc