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
when
expression is the following:Note that in this case the
else
case is necessary aswhen
must be exhaustive as it's used as en expression, i.e. it must cover all possible values ofc
. Ifc
were aBoolean
for example (or anenum
or any other value with a limited domain), then you could have covered all possible cases without anelse
case, so the compiler would have allowed the following:when
doesn't need to be exhaustive if it's not used as an expression but as a traditional control flow statement (like pre-Java 12switch
statement), as in the following snippet: