When Expressions in Kotlin
If you are coming from java background, you might have used switch statements.Similar switch kotlin have when.
For conditional expression with multiple branches, we can use when in kotlin.
“When” can be used multiple ways. A simple form looks like this
when(input){
1 -> println("input value is 1")
2 -> println("input value is 2")
else -> println("input value is different")
}
You can use when with multiple cases with common behaviour,for that you have to combine their condition in one line separated by commas
when(input){
1,2 -> println("input value is 1 or 2")
else -> println("input value is different")
}
One more use case is you can use arbitrary expressions(not only constants) as branch condition
when(input){
parseInt(str) -> println("input value is 1")
else -> println("input value is different")
}
you can check the value is in a range of valid numbers or collection also
when (input) {
in 1..10 -> print("input is in the range")
in validNumbers -> print("input is valid")
!in 10..20 -> print("input is outside the range")
else -> print("none of the above")
}
Another option is checking is or !is of a particular type.
when(x) {
is String -> x.startsWith("prefix")
else -> false
}
Compared to switch ,when have options to check multiple ways.
And It’s easy to use also.
That’s it about when
Happy Reading….Happy Coding…