1.1.50.2. fejezet, Folyamat vezérlés - többszörös elágazás

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> {
        print("x is neither 1 nor 2")
    }
}
when (x) {
    0, 1 -> print("x == 0 or x == 1")
    5..10 -> print("x in range 5..10")
    else -> print("otherwise")
}

Felsorolt típura alkalmazva:

enum class Bit {
    ZERO, ONE
}
 
val numericValue = when (getRandomBit()) {
    Bit.ZERO -> 0
    Bit.ONE -> 1
    // 'else' is not required because all cases are covered
}

Megadható kifelyezés is:

when (x) {
    s.toInt() -> print("s encodes x")
    else -> print("s does not encode x")
}

Értékhatárok ellenőrzésére is szolgálhat:

when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("none of the above")
}

Okos típusváltással:

fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix")
    else -> false
}

If - else - if kiváltása:

when {
    x.isOdd() -> print("x is odd")
    y.isEven() -> print("y is even")
    else -> print("x+y is odd")
}

a when egy függvény törzseként:

fun Request.getBody() =
    when (val response = executeRequest()) {
        is Success -> response.body
        is HttpError -> throw HttpException(response.status)
    }