# when Expressions and Ranges — Kotlin

Source: https://www.skillbyai.com/en/kotlin/n-when

> A powerful replacement for switch.

## Branching as an expression

`when` matches a value against branches and, like `if`, is an **expression** that produces a value. Branches can be constants, several values separated by commas, `in` a range or collection, `is` a type check, or arbitrary boolean conditions when `when` has no subject. When used as an expression, `when` must be **exhaustive**, usually via an `else` branch, or by covering every case of an enum or sealed type. **Ranges** such as `1..10` (inclusive), `0 until n` or `0..<n` (end exclusive), `10 downTo 1` and `step 2` are used in loops and `in` checks.

## Grading with when and ranges

when returns a value.

```kotlin
fun grade(score: Int): String = when (score) {
    in 90..100 -> "A"
    in 75..<90 -> "B"
    in 50..<75 -> "C"
    in 0..<50 -> "F"
    else -> throw IllegalArgumentException("score out of range: $score")
}

fun describe(x: Any): String = when {
    x is String && x.isEmpty() -> "empty string"
    x is Int && x % 2 == 0 -> "even number"
    else -> "something else"
}

fun main() {
    for (i in 10 downTo 0 step 5) println(i)
    for (i in 0..<3) println(grade(40 + i * 25))
}
```

## A mail sorter

`when` is like a sorting desk: each letter is checked against labelled slots in order and lands in the first slot that matches, with `else` as the catch-all tray.

**Quiz:** Which range excludes its end value?

- [ ] `0..5`
- [x] `0..<5` (or `0 until 5`)
- [ ] `5 downTo 0`
- [ ] `0..5 step 1`

*Answer:* `0..<5` (or `0 until 5`). `..` is inclusive; `..<` and `until` exclude the end.
