Search⌘ K

Conditions as Expressions

Explore how Kotlin treats if and when as expressions rather than statements, allowing you to assign values directly from conditional logic. Learn about exhaustive conditions, eliminate the need for a ternary operator, and understand best practices for using these expressions in your Kotlin code, preparing you to write more idiomatic and concise programs.

In Kotlin, both if and when can be used as expressions instead of statements. An expression is a piece of code that has a value, e.g. "Kotlin", 42 * 17, or readInput(). In contrast, a statement is a piece of code with no value, such as fun foo() { ... } or while (active) { ... }. In many programming languages, if and when/switch are statements. But in Kotlin, they are expressions! Let’s explore how this works.

Expressions with if #

Recall this listing from the lesson on if statements:

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

If you think about it, it seems that the relevant data that changes here based on the condition is the radius. So let’s store that in a variable by using an if ...