If I used the example from the docs,
class SomeActivity : AppCompatActivity() {
sealed class Expr
data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()
}
it does not compile, with the error:
Cannot access '<init>', it is private in 'Expr'.
However, moving it outside the enclosing class makes it compile:
sealed class Expr
data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()
class SomeActivity : AppCompatActivity() {
}
Why is this so? Is this an intended behavior? The docs does not seem to mention this.
Implementing Kotlin Sealed Classes To specify a sealed class, you need to add the modifier sealed . A sealed class cannot be instantiated. Hence, are implicitly abstract.
Here, we have a data class success object which contains the success Data and a data class Error object which contains the state of the error. This way, Sealed classes help us to write clean and concise code! That's all the information about Sealed classes and their usage in Kotlin.
A sealed class, in C#, is a class that cannot be inherited by any class but can be instantiated.
Kotlin has a great feature called sealed class, which allow us to extend an abstract class in a set of fixed concrete types defined in the same compilation unit (a file). In other words, is not possible to inherit from the abstract class without touching the file where it is defined.
Yes, it turns out to be intended behavior. According to the proposal allowing non-nested subclasses:
Proposal: allow top-level subclasses for a top-level sealed class in the same file.
For a non top-level sealed class all subclasses should be declared inside it. So, for such classes nothing changes.
The scenario you want is listed as an open question. There is a ticket for it at https://youtrack.jetbrains.com/issue/KT-13495. Nobody seems to be working on it at the moment. In the discussion of the proposal, the developer says:
Well, there is some not-trivial implementations details(about generation synthetic constructors) which was solved for top-level classes but how do it in general is not clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With