0

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?

Tim Kochetkov
  • 149
  • 1
  • 11
  • 3
    `SubClass4` is not a subclass of `Class4`. It's _nested_ inside `Class4`, but it's not a subclass. Same with `SubClass2` and `Class2`. – Slaw Aug 31 '23 at 20:06
  • See https://kotlinlang.org/docs/inheritance.html for more information – Slaw Aug 31 '23 at 20:09
  • 2
    It has nothing really to do with sealed classes. It is only about if we subclass another class or not. – broot Aug 31 '23 at 20:22
  • Thank you for the clarifications, I had such a suspicion. My initial problem was to do with Android and how I often had to create sealed classes/interfaces, from the purpose of using "when" statement. I've just tested and "when" indeed does not work with nested classes, only with subclasses. I was confused for a moment because I'd never thought about it before. – Tim Kochetkov Aug 31 '23 at 20:49

0 Answers0