Kotlin "when" without break (option that switch case in java had)

Viewed 1639

When I write:

num = 3
switch (num){
        case num < 2:
            Log.d("int", "3");
        case num > 2:
            Log.d("int", "2");
        case num > 0 :
            Log.d("int", "1");
        case num > 40:
            Log.d("int", "10");
    }

This will print case 2 and case 3.

I want to do the same in kotlin without using multiple if/else statements in situations like this. When{} doesn't help me since as AFAIK it has a mandatory break when we enter case and it doesn't go further through cases. Does anyone know nice solution for this?

1 Answers

What you're asking is allowing fallthrough in switch statements. Kotlin does not support this with when.

Allowing fallthrough can easily cause bugs as it's not explicit enough. Jetbreans team seems to have a "tentative plan" of supporting the continue keyword in when statements to allow fallthrough. That would make it explicit.

Some workarounds are suggested in stackoverflow, but using multiple if statements is probably the cleanest way going forward with Kotlin right now.

Here's the discussion in kotlinlang about this: https://discuss.kotlinlang.org/t/fall-through-in-when/2540

Related