Nested when with a sealed class

I have the following code which does not compile:

fun main(args: Array<String>) {
  val week: Week = Week.Saturday()
  val name = when (week) {
    is Week.Monday -> week::class.qualifiedName
    is Week.Tuesday -> week::class.qualifiedName
    is Week.Wednesday -> week::class.qualifiedName
    else -> when (week) {
        is Week.Thursday -> week::class.qualifiedName
        is Week.Friday -> week::class.qualifiedName
        is Week.Saturday -> week::class.qualifiedName
        is Week.Sunday -> week::class.qualifiedName

sealed class Week {
  class Monday : Week()
  class Tuesday : Week()
  class Wednesday : Week()
  class Thursday : Week()
  class Friday : Week()
  class Saturday : Week()
  class Sunday : Week()

nested when expression covers all remaining branches of the outer when. But I still get an error on the inner when saying that it should be exhaustive.

1 Like

The behavior is what I’d have expected and the ‘when’ expression is simply doing what it says on the tin.

The compiler is happy with the outer ‘when’ because it has an ‘else’ branch but is unhappy with the inner one because it lacks one and is not exhaustive.

Although your example is straightforward, I think that in general it would be asking too much (i.e. too slow and complex) for the compiler to consider nested 'when’s and other complex statements when doing its exhaustiveness check.

1 Like

Your inner ‘when’ is not, in and of itself, exhaustive. Though you have used up the other possibilities in the outer ‘when’, that is not taken into consideration on the inner ‘when’. If you include all of Sunday through Saturday in the inner ‘when’, then it would consider that to be exhaustive.

1 Like

Is there any update on this, or is it indeed deemed to slow?

I needed this for a when which sets the value on some cases:

    ASealedClass.First->println("not needed")
    else -> stateflow.value = when(aSealedClass) {
        ASealedClass.Second -> "sec"
        ASealedClass.Second -> "sec"
1 Like