beginner18 min

Control Flow: if as an Expression, when, and for

Kotlin's if-as-expression, the powerful when construct, and for loops.

What you'll learn

  • Use if as an expression that produces a value, not just a statement
  • Use when as Kotlin's more powerful replacement for a traditional switch
  • Write a for loop over a range or collection

Explanation

In Kotlin, if can be used as an expression that produces a value: val max = if (a > b) a else b -- there's no separate ternary operator because if-as-expression already covers that need.

when is Kotlin's replacement for a traditional switch statement, but more powerful: it can match exact values, ranges, types, or arbitrary boolean conditions, and (like if) can be used as an expression: val description = when (score) { in 90..100 -> "A"; in 80..89 -> "B"; else -> "C or below" }. An else branch is required when when is used as an expression, to guarantee it always produces a value.

for loops commonly iterate over a range (for (i in 1..5), inclusive of 5) or a collection (for (item in list)). Kotlin has no traditional C-style for (int i = 0; i < n; i++) loop -- ranges and collection iteration cover that need more safely and readably.

Guided lab

Predict: when as an expression

KotlinNot executed
This lab does not run in your browser or on VisaSparkSchools's servers. Read the code, predict what it does, then reveal the real expected output.

Read this program and predict exactly what it prints.

fun main() {
    val score = 85
    val grade = when {
        score >= 90 -> "A"
        score >= 80 -> "B"
        score >= 70 -> "C"
        else -> "F"
    }
    println("Grade: $grade")

    for (i in 1..3) {
        println("Attempt $i")
    }
}

Stuck? Get a hint.

Common mistakes

  • Looking for a separate ternary operator (`a ? b : c`) -- Kotlin uses if-as-expression instead.
  • Forgetting the `else` branch when using `when` as an expression, which is required so it always produces a value.
  • Using `0 until n` (exclusive) when `1..n` (inclusive) was intended, or vice versa, and getting an off-by-one range.

Knowledge check

Knowledge check

1. How does Kotlin implement what other languages call a ternary operator?
2. What is required when `when` is used as an expression (to produce a value)?
3. What does `1..5` represent as a range in a for loop?

Takeaway

Use if and when as expressions that produce values, and remember 1..5 is inclusive while 0 until n is exclusive.

Summary

if and when can both be used as value-producing expressions; when is a more powerful switch; for iterates ranges/collections, with inclusive .. and exclusive until.

References

Your notes

Notes save automatically.

Finished this lesson?

Mark it complete to track your progress and schedule a future review.

Next: Null Safety