when is the replacement of the switch operator of java. Block of code will executed when some condition is satisfied, also when expression can returns value
using braces we can use multiple statements.
it can also be used as a statement without any other branch. Let’s take an example.
Example 1:
fun main(){
var x = 44
var selectedNumber = when(x) {
1 -> "One"
2 -> "Two"
3 -> "Three"
else -> "Invalid"
}
println(selectedNumber) // Invalid
}
Example 2:
fun main(){
var x = 2
var selectedNumber = when(x) {
1 -> "One"
2 -> {
println("Hello number Two")
"Two" // returns value
}
3 -> "Three"
else -> "Invalid"
}
println(selectedNumber)
}
output:
Hello number Two
Two
Combine multiple branches using comma separated :
fun main(){
var x = 1
when(x) {
1,2,3 -> println("Hello")
4,5,6 -> println("Hi")
7,8,9 -> println("Hola")
else -> println("No Greeting")
}
}
Output:
Hello
Check the value if input value in the range or not using in operator :
if pass value in when expression matches with any condition that branch will execute
fun main (args:Array<String>) {
val x = 15
when(x) {
in 1..5 -> print("number is between 1 to 5")
in 5..10 -> print("number is between 5 to 10")
!in 1..12 -> print("Invalid Number")
}
}
output
Invalid Number