0
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?

Rakla i
  • 1
  • 2
  • Sadly kotlin `when` does not support fall-through like java switch. [Related question](https://stackoverflow.com/questions/30832215/when-statement-vs-java-switch-statement). – Pawel Apr 21 '19 at 13:32

1 Answers1

2

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
}
user2340612
  • 10,053
  • 4
  • 41
  • 66
  • 1
    Why not `'a', 'd', 'e' -> 100`? – forpas Apr 21 '19 at 12:00
  • Thanks for your the fastest answer, but I have some question in that kotlin case. In the switch-case code, if var c has 'a', then num will have 210 by including the process in case 'c' & case 'd', 'e', but the code in your answer, with a condition c = 'a', can't make that num has 210 by not including the process in case 'c'. I felt some lack of demonstration, so I added my trying in my question. – Rakla i Apr 21 '19 at 12:55
  • 1
    @raklai what you're looking for is called `fallthrough` and it's the default behaviour of Java's `switch` but unfortunately it's not available (yet) in Kotlin as of version 1.3 so you can replace it with a series of `if` statements for instance – user2340612 Apr 21 '19 at 13:54