Kotlin Tutorial · Kotlin Basics · Lesson 7 of 31

Kotlin if and when

Branch with if and when, both of which are expressions that return a value.

Create a free account to save this page, take notes and track your progress. Sign in

if is an expression

if returns a value, so Kotlin has no ternary operator: write val x = if (a) b else c.

if as an expression
fun main() {
    val total = 75
    val label = if (total > 50) "large order" else "small order"
    println(label)

    val shipping = if (total >= 60) {
        println("Free shipping applied")
        0
    } else {
        5
    }
    println("Shipping: $shipping")
}

Output

large order
Free shipping applied
Shipping: 0

Run this on your computer — see “Get Started” for setup.

when

when replaces switch and is far more flexible: match values, several values at once, ranges, types, or use it without an argument as a cleaner if/else if chain. Used as an expression, it must cover every case (usually with else).

when with values, ranges and conditions
fun describe(code: Int): String = when (code) {
    200, 201 -> "success"
    in 300..399 -> "redirect"
    404 -> "not found"
    in 500..599 -> "server error"
    else -> "other"
}

fun main() {
    for (code in listOf(200, 301, 404, 503, 418)) println("$code ${describe(code)}")

    val temperature = 31
    val advice = when {
        temperature > 30 -> "stay in the shade"
        temperature < 5 -> "wear a coat"
        else -> "enjoy the day"
    }
    println(advice)
}

Output

200 success
301 redirect
404 not found
503 server error
418 other
stay in the shade

Run this on your computer — see “Get Started” for setup.

Test yourself

What replaces the ternary operator (a ? b : c) in Kotlin?

  1. a ?: b
  2. if (a) b else c, because if is an expression
  3. when (a) b c
  4. Kotlin has a ternary operator
Show answer

Answer: if (a) b else c, because if is an expression

Was this page helpful?