[SOLVED] 'when' expression recommended to be exhaustive, even if it is impossible to reach the else branch


Given the following code:

fun main(args: Array<String>) {
    val enumValue = SomeEnum.C

    if (enumValue != SomeEnum.A) {
        // Prepare for op
        when (enumValue) {
            SomeEnum.B -> TODO("Some op with B")
            SomeEnum.C -> TODO("Some op with C")
        // Do some op common to B and C
    } else {
        // Do a op exclusive to A

enum class SomeEnum { A, B, C }

I get this warning on the when keyword:

‘when’ expression on enum is recommended to be exhaustive, add ‘A’ branch or ‘else’ branch instead

But, as far as I know, it would be imposible to reach the 'A' branch or the 'else' branch.

Is this intended, or maybe a bug?


I guess this is neither intended nor a bug. My guess on how this warning is implemented is that it checks if all different enum cases are checked inside of the when-expression. I don’t think the compiler is looking at any code outside of the when-expression. I guess in this case it is possible to argue that the compiler should now that this when expression is exhaustive but I feels this would just lead far more complexity in the compiler without much gain. If this would be an error and not a warning I would consider this a bug, but in this case I would add a 3rd branch which would throw an error or just suppress the warning for this expression.
This would also lead to more readable code IMO because the when would explicitly state, that the case C is not supposed to be handled here instead of being just forgotten.
But that’s just my opinion on the subject. I don’t think there is a right or wrong way to handle this problem.


I actually had a similar problem to this myself today and, knowing that it would never be reached, I simply added the following at the end of my when statement to deal with it:

else -> {}

Other than this or suppressing the warning you could also:

  1. Change your SomeEnum.C case to else.

  2. Use if/else instead of when.

I’m virtually certain that this is not a bug. It’s simply - as @Wasabi375 said - that it’s not really practical for the compiler to look outside the when statement to decide whether it’s exhaustive or not.

This inevitably leads to situations where the programmer knows that the when statement is effectively exhaustive but the compiler doesn’t.

Even so, I think on balance it’s better for the compiler to issue a warning here because, if it’s not actually exhaustive, it might alert you to what might otherwise be a difficult bug to identify where you’d failed to code for all possibilities.


Okey, thank you guys for your suggestions :+1: