Conditions as Expressions

Learn how to use conditions in Kotlin as expressions, including assigning different values to a variable depending on a condition.

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:

Get hands-on with 1000+ tech skills courses.