Explain advantages of when vs switch in Kotlin

Technology CommunityCategory: KotlinExplain advantages of when vs switch in Kotlin
VietMX Staff asked 3 years ago

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 switchwhen 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
}