Question - What are the advantages of "when" over "switch" in Kotlin?
Answer -
The "switch" is used in Java, but in Kotlin, that switch gets converted to "when". When has a better design as compared to "switch", and it is more concise and powerful than a traditional switch. We can use "when" either as an expression or as a statement.
Following are some examples of when usage in Kotlin:
In 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
}