How can kotlin's 'when' expression make a process as this switch-case code?

1.8k views Asked by At
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?

1

There are 1 answers

3
user2340612 On

In Kotlin the equivalent when expression is the following:

val c = // some char
val num = 100 + when (c) {
    'c' -> 10
    'a', 'd', 'e' -> 100
    else -> 0
}

Note that in this case the else case is necessary as when must be exhaustive as it's used as en expression, i.e. it must cover all possible values of c. If c were a Boolean for example (or an enum or any other value with a limited domain), then you could have covered all possible cases without an else case, so the compiler would have allowed the following:

val c = // some boolean
val num = 100 + when (c) {
    true -> 10
    false -> 0
}

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 12 switch statement), as in the following snippet:

val c = // some char
var num = 100

when (c) {
    'a', 'd', 'e' -> num += 100
    'c' -> num += 10
}