typestar

when in Kotlin

The switch that matches ranges, lists of values, and bare conditions.

fun main() {
    val windKmh = 38
    // when replaces switch; ranges and commas both guard a branch.
    val flag = when (windKmh) {
        in 0..11 -> "calm"
        in 12..29 -> "breezy"
        30, 31 -> "gusty"
        else -> "stay off the ridge"
    }
    println("Wind $windKmh km/h: $flag")

    // Without a subject, each branch is a full condition.
    val season = "fall"
    when {
        season == "winter" -> println("Hut stove is lit")
        else -> println("Cold water only")
    }
}

How it works

  1. when (windKmh) tests the subject against each branch in order.
  2. in 0..11 matches a range; 30, 31 matches either value; else catches the rest.
  3. A subjectless when chains full boolean conditions like an if ladder.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
420
Tokens
102
Three-star pace
70 tpm

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

Type this snippet

Step 2 of 3 in Control flow, step 5 of 27 in Language basics.

← Previous Next →