I can't have nested sealed classes?

This code compiles fine at the top of the file:

sealed class Change {}
data class FilterChange(val name: FilterName): Change()
object SortChange: Change()

But if I put it inside another class, I get errors on lines 2 and 3 saying: Cannot access '<init>': it is private in 'Change'.

What’s the recommended way to nest this group of classes inside another class?


It is annoying, but you will need to nest the subclasses inside of the sealed class.

1 Like

Not sure what are you talking about. You can.

Your example code is what fatjoe79 recommended, but it’s not what I wrote in my original question. I had the subclasses at the same level of the sealed base class (not inside it).

Not sure if it’s possible then. Putting the inheriting classes in the top level scope is a special case that is allowed for top level sealed classes. Maybe this could be changed so it works for nested classes as well. You could create a feature request at https://kotl.in/issue

It looks like, in the future, sealed classes may be able to have inheritors anywhere in the same module


Roman Elizarov: Moreover, we want to lift the restriction on sealed class from a single file to a single module.

Edit: Here’s an issue specifically for what you want to do, and it’s targeted for Kotlin 1.5: