int num = 100;
char c = 'a';
c = someBigTask(c);
switch (c) {
case 'a':
num += 100;
case 'c':
num += 10;
case 'd':
case 'e':
num += 100;
}
I want to eliminate same code by 'when' expression in another condition like this switch-case code, but I couldn't find the solution..
I did like this for this problem:
var num = 0
when(c){
'a' -> num += 100
'a', 'c' -> num += 10
'a', 'c', 'd', 'e' -> num += 100
else -> 0
}
and I getted the result excuted only 'a' -> num += 100..
Can I get the solution with only 'when' expression in this problem?
In Kotlin the equivalent
whenexpression is the following:Note that in this case the
elsecase is necessary aswhenmust be exhaustive as it's used as en expression, i.e. it must cover all possible values ofc. Ifcwere aBooleanfor example (or anenumor any other value with a limited domain), then you could have covered all possible cases without anelsecase, so the compiler would have allowed the following:whendoesn't need to be exhaustive if it's not used as an expression but as a traditional control flow statement (like pre-Java 12switchstatement), as in the following snippet: