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?
2 Likes
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.
https://pl.kotl.in/WD7y-ds3N
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
https://youtrack.jetbrains.com/issue/KT-20423#focus=Comments-27-4196974.0-0
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:
https://youtrack.jetbrains.com/issue/KT-13495