typestar

if is an expression in Kotlin

Kotlin has no ternary because if itself returns a value.

fun main() {
    val clouds = 7
    // if is an expression: both branches yield a value.
    val sky = if (clouds > 5) "overcast" else "clear"
    println("Sky report: $sky")

    // Branches may be blocks; the last line is the value.
    val advice = if (sky == "clear") {
        "carry sunscreen"
    } else {
        "pack the rain shell"
    }
    println(advice)
}

How it works

  1. val sky = if ... else ... binds whichever branch runs.
  2. Block branches work too: the block's last line is its value.
  3. Both arms must exist when the result is used — no silent nulls.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
318
Tokens
63
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 50 seconds.

Type this snippet

Step 1 of 3 in Control flow, step 4 of 27 in Language basics.

← Previous Next →