The when
expression in Kotlin takes a value as input and checks the value against the condition provided.
If there is a match present for the value passed to the when
expression, then the matched condition block will be executed. We should add the else
branch to the when
expression. The else
branch will be executed when no condition is matched (like the default case in the switch statement). If the else
condition is not included in the code and the statement does not match any when
condition, then we will get an
It is like a modified version of the switch statement with a return value.
fun main(args : Array<String>) {val day = "Sunday"val dayType = when(day) {"Sunday" -> "Weekend""Saturday" -> "Weekend"else -> "Working days"}println("$day is $dayType")}
In the code above, we have created a day
variable with the Sunday
value, and passed it to the when
expression. Inside the when
expression, the value is matched with the available conditions. The day
variable matches with the “Sunday” value, so it will return the Weekend
as the return value of the when
expression.
We can combine multiple conditions into a single block.
fun main(args : Array<String>) {val day = "Sunday"val dayType = when(day) {"Monday", "Tuesday", "Wednesday" -> "First half""Thursday", "Friday" -> "Second half"else -> "Week end"}println("$day is $dayType")}
In the code above, we have added multiple conditions to a single block. If one of the conditions satisfies the value passed to the when
expression, then that block will be executed.
We can use an expression as a condition.
fun main(args : Array<String>) {val char1 = "A"val char2 = "a"when(char1) {char2.toUpperCase() ->{println(char2)}else -> {println("Not equal")}}}
In the code above, we have used the char2.toUpperCase()
expression as a condition to the when
expression. We also skipped the return value and handled inside the condition block.
in
operator as a conditionfun main(args : Array<String>) {val experienceInYears = 5val status = when(experienceInYears) {0 -> "Trainee"in 1..2 -> "Junior Deveoper"in 3..5 -> "Senior Developer"in 6..10 -> "Product Manager"in 11..20 -> "Manager"else -> "Fire him/her"}println(status);}
In the code above, we used the in
operator inside of the when
block to check if the value was present in the range.
Free Resources