Kotlin, sealed classes, children do not have to extend the parent class

144 views Asked by At

There is no information about this in the official Kotlin docs, or I've missed it (here: https://kotlinlang.org/docs/sealed-classes.html)

Although through testing I assume that my understanding is correct:

you can omit specifying the supertype of children of a sealed class as the parent class' type if you do not need a child to access the sealed class' constructor parameters.

In some way it is counterintuitive for me, but I can see possible usages.

The purpose of the question is to know if I can sometimes write less code this way.

I have a simple example here:

object SealedClassesTest2 {

sealed class Class1 {
    data class SubClass1(val value: String) : Class1()
}

sealed class Class2 {
    data class SubClass2(val value: String)
}

sealed class Class3(val parentVal: String) {
    data class SubClass3(val value: String) : Class3("Class3")
}

sealed class Class4(val parentVal: String) {
    data class SubClass4(val value: String)
}

@JvmStatic
fun main(args: Array<String>) {
    val subClass1 = Class1.SubClass1("SubClass1")
    val subClass2 = Class2.SubClass2("SubClass2")
    val subClass3 = Class3.SubClass3("SubClass3")
    val subClass4 = Class4.SubClass4("SubClass4")
    println(subClass1.value)
    println(subClass2.value)
    println(subClass3.value)
    println(subClass3.parentVal)
    println(subClass4.value)
}

}

Output:

SubClass1
SubClass2
SubClass3
Class3
SubClass4

Here Class1 and Class2 have identical behaviour, even though I do not call the Class2 constructor for the SubClass2. There are no errors in compilation or runtime.

For the Class3 and Class4 there are still no errors in compilation or runtime, but the difference is that I can address the subClass3.parentVal but do not have the access to subClass4.parentVal (because I haven't called the Class4 constructor for the SubClass4)

I assume that when there are no parameters for the parent sealed class, I can skip calling its constructor for child classes, and the compiler does not see any difference.

Is that correct?

0

There are 0 answers