Compiler requires help with smart casting and sealed classes


#1

In this example a sealed class B implements an interface A. After a smart cast of A to B I would expect an exhaustive when comprehension to only require cases for each subclass of B. However the following does not compile.

interface A

sealed class B : A {
    class B1 : B()
}

fun f(a: A) =
        if (a is B) {
            when (a) {
                is B.B1 -> "B1"
            }
        } else {
            "Not a B"
        }

This will compile if we help the compiler by explicitly stating when(a as B). However, this should not be necessary and Idea actually flags it as redundant.

Note that the same happens if the if is replaced with another when


#2

It’s a bug: https://youtrack.jetbrains.com/issue/KT-14626, thank you. Possible workaround:

fun f(a: A) = 
        (a as? B)?.let { 
            when (it) {
                is B.B1 -> "B1"
            }
        } ?: "Not a B"