Conditions with `when`
Understand Kotlin's `when` construct and best practices of using `if` vs `when`.
We'll cover the following...
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:
Press + to interact
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. ...
Ask