Can I avoid unnecessary else in when block?


#1

I have a lambda like this:

{
    val vert = it / 4
    when (it % 4) {
        0 -> ...
        1 -> ...
        2 -> ...
        3 -> ...
        else -> ...
    }
}

The else is necessary because IDEA/the compiler doesn’t realise that it % 4 can’t result in any other value (the lambda is for an Array constructor so it is a positive integer). Is there a way I can avoid the else, eg with an annotation? Or would it be reasonable to ask that the compiler be smart enough to spot this situation?


#2

There isn’t really a way to avoid this. The compiler expects the lambda to end with an expression and, if ‘when’ is used as an expression, it must have an ‘else’ clause (unless exhaustive enum or sealed classes are being used) to ensure all possibilities are covered.

What I tend to do in this sort of situation is to omit the separate ‘3’ clause and just use ‘else’ to represent this case:

{
    val vert = it / 4
    when (it % 4) {
        0 -> ...
        1 -> ...
        2 -> ...
        else -> ...  // i.e. 3
    }
}

It isn’t perfect but at least it avoids redundant code.


#3

Thanks, that’s a neat solution.