How to construct java sealed class in kotlin? It's...
# getting-started
s
How to construct java sealed class in kotlin? It's will
Sealed types cannot be instantiated
when try to init
m
You cannot instantiate a sealed class much less that you can instantiate an enum without a value. There is no such thing as 'just' a 'Planet class' in the
enum planet { EARTH, MARS, etc. }
r
What do you want to achieve? A sealed hierarchy or a class that cannot be subclassed?
s
I can init java sealed class in java but not in kotlin. It's "Java Sealed Class" instead of kotlin one
x
The Java equivalent Kotlin sealed class is an abstract class. You can't instantiate a sealed class for the same reason you cab't instantiate an abstract class
d
What is a java sealed class?
Ah, new in Java 15.
I see. Kotlin assumes sealed classes are always abstract, so can't be instantiated, where Java doesn't have such a limitation.
So, in Java, you can instantiate the base class if it isn't abstract, but in Kotlin you can't.
You can get around this by creating a utility method in Java that does the instantiation, but it appears you can't do it in pure Kotlin.
Copy code
sealed class Foo permits Bar {
    static @NotNull Foo instance() {
        return new Foo();
    }
}
Then in Kotlin, you can call Foo.instance()
1
👍 1