When to use the Kotlin "when" expression

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 errorerror: ‘when’ expression must be exhaustive, add necessary ‘else’ branch.

It is like a modified version of the switch statement with a return value.

Example

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.


Example of handling multiple conditions

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.


Using an expression as a condition

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.


Using the in operator as a condition

fun main(args : Array<String>) {
val experienceInYears = 5
val 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

Copyright ©2025 Educative, Inc. All rights reserved