0Pricing
Kotlin Academy · Lesson

when as Expression

Return values from when.

when as an Expression

Kotlin's when is more than a switch statement. It is an expression, meaning it produces a value you can assign or return.

This makes branching logic concise and readable.

Returning a Value

When used as an expression, each branch supplies a result. The matching branch's value becomes the whole when result.

fun main() {
    val day = 3
    val name = when (day) {
        1 -> "Monday"
        2 -> "Tuesday"
        3 -> "Wednesday"
        else -> "Other"
    }
    println(name)
}

All lessons in this course

  1. when as Expression
  2. Smart Casts
  3. is and as Operators
  4. Exhaustive when
← Back to Kotlin Academy