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?
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.
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.
it can be used without an argument.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With