Conditions as Expressions
Learn how to use conditions in Kotlin as expressions, including assigning different values to a variable depending on a condition.
We'll cover the following...
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:
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
...