if, when, Ranges & Loops

Expressions instead of statements, the powerful when, ranges and loops with labels.

In Kotlin, if and when are expressions that return values, so the ternary operator is not needed. when replaces switch and long if-else chains, and ranges make loops and range checks readable.

Control flow

classify returns the value of its if-else chain directly.

when (code) matches values, lists (10, 11) and ranges (in 1..9); else is required when not every case is covered.

1..5 includes 5; 0 until 10 excludes 10; step and downTo change the direction and stride.

when without an argument evaluates conditions in order.

withIndex gives index and value; break@outer leaves the outer loop.

val max = (a > b) ? a: b val max = if (a > b) a else b Kotlin has no ternary operator because if is already an expression.

What does x in 1..10 mean?

A range check: true when 1 <= x <= 10.