Junior — Middle
Is it possible to declare a sealed class with an internal modifier in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, you can declare a sealed class, and inner classes within it can have the inner modifier. However, for a class to be inner, it must be declared inside another class (not directly in a file), and have access to the instance of the outer class.
Example:
sealed class Outer {
inner class Inner : Outer() {
fun accessOuter() = this@Outer
}
}
If the sealed class is declared at the top level, then inner classes cannot be inner, as there is no outer instance. In this case, inner classes will simply be nested, without access to an outer object.
Thus, the inner modifier is possible if the sealed class is an outer class, and the nested class is declared inside it with inner.