Search⌘ K

Conditions with `when`

Explore how to apply Kotlin's when expression to perform clear and flexible conditional checks. Learn to replace multiple if conditions with when statements using fixed values, ranges, types, and complex boolean expressions for more concise and readable code.

Conditions Using when #

You can use when conditions to define different behaviors for a given set of distinct values. This is typically more concise than writing cascades of if-else if conditions. For instance, you can replace the if condition above with a when condition to save around 30% of the lines of code in this example:

Kotlin
when (planet) {
"Jupiter" -> println("Radius of Jupiter is 69,911km")
"Saturn" -> println("Radius of Saturn is 58,232km")
else -> println("No data for planet $planet")
}

The when keyword is followed by the variable it compares against. Then, each line defines the value to check on the left-hand side, followed by an arrow -> and the block of code to execute if the value matches.

The code block on the right-hand side must be wrapped in curly braces unless it’s a single expression. ...