Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sealed classes inside another class in Kotlin can't be compiled: cannot access '<init>' it is private

Tags:

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.

like image 903
Randy Sugianto 'Yuku' Avatar asked Jun 27 '18 04:06

Randy Sugianto 'Yuku'


People also ask

How do you initialize a sealed class Kotlin?

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.

What is the sealed class in Kotlin?

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.

Can a sealed class inherit from another class?

A sealed class, in C#, is a class that cannot be inherited by any class but can be instantiated.

Can sealed class be inherited in Kotlin?

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.


1 Answers

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.

like image 145
Alexey Romanov Avatar answered Sep 28 '22 03:09

Alexey Romanov