https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Settingdust

12/07/2023, 6:17 AM
How to construct java sealed class in kotlin? It's will
Sealed types cannot be instantiated
when try to init
m

Michael de Kaste

12/07/2023, 8:00 AM
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

Ronny Bräunlich

12/07/2023, 1:12 PM
What do you want to achieve? A sealed hierarchy or a class that cannot be subclassed?
s

Settingdust

12/07/2023, 2:17 PM
I can init java sealed class in java but not in kotlin. It's "Java Sealed Class" instead of kotlin one
x

xoangon

12/07/2023, 6:59 PM
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

Daniel Pitts

12/07/2023, 9:05 PM
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