I just ran into a interesting situation. Normally when you use if ... else
as an expression you can not emit the else branch and I understand why. But let’s look at this situation
enum SomeEnum {
A,
B
}
fun foo(e: SomeEnum): Unit = when(e) {
A -> {
doSomething()
if(someCondition) {
doSomethingElseAsWell()
}
}
B -> ...
}
Compiling this fails with this error
‘if’ must have both main and ‘else’ branches if used as an expression
I can fix it by adding an empty else
branch, but this looks stupid. I could also not use an expression body for the function but in that case I loose the check that I am exhaustive with my when
expression.
I wonder if this is something that should be changed, so that if an if
-expression returns Unit
it can omit the else
branch. Any thoughts?