tonicsoft
tonicsoft

Reputation: 1808

Why can't I declare a nested class that is a subclass of a sealed class?

The Kotlin documentation states:

A sealed class can have subclasses, but all of them must be declared in the same file as the sealed class itself. (Before Kotlin 1.1, the rules were even more strict: classes had to be nested inside the declaration of the sealed class).

Admittedly, this is worded as a necessary but not sufficient condition, but it does imply (by lack of anything contrary) that I can declare a subclass of a sealed class anywhere in the same file.

Given that the following code compiles:

//class Jungle {
    sealed class Animal
    class Tiger : Animal()
//}

why does the following not compile:

class Jungle {
    sealed class Animal
    class Tiger : Animal()
}

The second snippet gives the following errors with Intellij Kotlin plugin version 1.3.72-release-IJ2020.1-5:

Error:(3, 20) Kotlin: Cannot access '<init>': it is private in 'Animal'
Error:(3, 20) Kotlin: This type is sealed, so it can be inherited by only its own nested classes or objects

In fact, the second error message here seems to directly contradict the documentation.

Upvotes: 1

Views: 2352

Answers (1)

k.wahome
k.wahome

Reputation: 1062

There is an open issue for it that also notes the misleading diagnostic message. But it seems the conversation around it died down.

Also, this Sealed class inheritance proposal from 4 years ago leaves the matter of sub-classing a nested sealed class by a class on the same level as an open question

Upvotes: 1

Related Questions