DEV Community

Discussion on: I've never become overly convinced that switch statements are that much cleaner than `if else if else if else if else`

Collapse
 
sierisimo profile image
Sinuhe Jaime Valencia

In kotlin we don't have a switch, we have a when operator:

fun doSomething(x: Int){
    when {
        x == 1 -> 
        x == 2 -> 
        else -> 
    }
}

It can take a parameter to match:

fun doSomething(x: Int){
    when(x) {
        1 -> 
        2 -> 
        else -> 
    }
}

And also you can put different stuff there…

fun doSomethingWithAFoo(foo: Foo){
    when(foo){
        is SubFoo -> {
          //…
        }
        foo.someProperty == someValue -> 
        else -> 
    }
}

in the case of is SubFoo you get auto-cast. So you can use foo as a SubFoo


For me more than 3 else-if will complicate the reading of the code and in some languages will get you a wrong scenario…

Like the kotlin syntax that actually doesn't have an else-if expression (yes, in kotlin is an expression) so you can end in weird places:

github.com/angryziber/kotlin-puzzl...

In kotlin else if(…) is actually: else { if() }

So that's one reason at least to prefer when over else-if in kotlin.