Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

kotlin

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?

like image 770
Kratos Avatar asked Mar 09 '21 09:03

Kratos


People also ask

Is Break statement necessary in switch-case in Java?

Technically, the final break is not required because flow falls out of the switch statement. Using a break is recommended so that modifying the code is easier and less error prone. The default section handles all values that are not explicitly handled by one of the case sections.

Does Kotlin need break?

In Kotlin, if a matching case is found, only the code in the respective case block is executed, and execution continues with the next statement after the when block. This essentially means that we don't need break statements at the end of each case block.

Can when statement in Kotlin be used without passing any argument?

it can be used without an argument.

How do I choose between switches and when in Kotlin?

In Java we use switch but in Kotlin, that switch gets converted to when. when is also used for conditional representation but it does the things in a very smarter and easier way. Whenever you are having a number of possibilities then you can use when in your code.


Video Answer


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

like image 175
furkan Avatar answered Sep 30 '22 22:09

furkan