0 votes
in Kotlin by
Explain advantages of when vs switch in Kotlin

1 Answer

0 votes
by
In Java we use switch but in Kotlin, that switch gets converted to when. When has a better design. It is more concise and powerful than a traditional switch. when can be used either as an expression or as a statement.

Some examples of when usage:

Two or more choices

when(number) {

    1 -> println("One")

    2, 3 -> println("Two or Three")

    4 -> println("Four")

    else -> println("Number is not between 1 and 4")

}

"when" without arguments

when {

    number < 1 -> print("Number is less than 1")

    number > 1 -> print("Number is greater than 1")

}

Any type passed in "when"

fun describe(obj: Any): String =

    when (obj) {

      1 -> "One"

      "Hello" -> "Greeting"

      is Long -> "Long"

      !is String -> "Not a string"

      else -> "Unknown"

    }

Smart casting

when (x) {

    is Int -> print("X is integer")

    is String -> print("X is string")

}

Ranges

when(number) {

    1 -> println("One") //statement 1

    2 -> println("Two") //statement 2

    3 -> println("Three") //statement 3

    in 4..8 -> println("Number between 4 and 8") //statement 4

    !in 9..12 -> println("Number not in between 9 and 12") //statement 5

    else -> println("Number is not between 1 and 8") //statement 6

}

Related questions

0 votes
asked May 26, 2022 in Kotlin by Robin
0 votes
asked May 26, 2022 in Kotlin by Robin
0 votes
0 votes
0 votes
0 votes
asked May 26, 2022 in Kotlin by Robin
...