I think the problem is that ABC and NABC classes are not sealed themselves.
I tried to mark them as sealed classes, but the compiler then doesn’t let me have inner objects extending them.
However, this works:
sealed class SC(open val connector: String)
sealed class NABC(override val connector: String) : SC(connector)
sealed class ABC(override val connector: String) : SC(connector)
object No : SC(" ")
object And : ABC("&")
object Or : ABC("|")
object Iff : NABC("<=>")
object Implies : NABC("=>")
fun test(sc: SC) = when (sc) {
No ->
println()
Or ->
println()
And ->
println()
Iff ->
println()
Implies ->
println()
}
So I believe it is a language/compiler limitation. Not sure if it’s intended or not.
The thing is, there could be classes outside the compiler’s knowledge (in a project that uses your code, for example) that inherit from NABC or ABC, which would break the when-expression as no branch would match them. The sealed keyword is made for exactly that purpose, to state “This class can’t be subclassed except for inside this file”.
Yes, absolutely sure. It’s not generally forbidden to inherit from sealed classes, just direct inheritance is forbidden. You can easily try it, create a sealed class A and an abstract class B inheriting from A. Now create another file with a third class C. Trying to let that class inherit from A won’t work, but it will be fine inheriting from B.