Kotlin Control
if and when
In Kotlin, both if and when can act as expressions that return a value—there is no separate ternary operator (?: is the Elvis operator for nulls). When when is used as an expression, the compiler enforces exhaustiveness so you cannot forget an else branch or a sealed-class case:
val count = 2
val message = if (count > 0) "positive" else "zero or negative"
// `when` replaces switch-case with ranges, type checks, and no fall-through
val category = when (count) {
0 -> "none"
in 1..3 -> "small"
else -> "large"
}
println("$message ($category)")
Loops and ranges
Kotlin replaces C-style three-part for loops with for (item in collection) and closed or half-open integer ranges. Use 1..5 for an inclusive range, 0 until size (or 0..<size in modern Kotlin) for zero-indexed bounds, and downTo / step for reverse or strided iteration:
for (i in 1..3) {
println("step $i")
}
// Half-open range prevents off-by-one errors when indexing
val items = listOf("a", "b", "c")
for (idx in 0 until items.size) {
println("$idx -> ${items[idx]}")
}
Break and continue
break exits the nearest enclosing loop and continue skips to the next iteration. For nested loops, Kotlin supports labeled jumps (outer@ for (...) { break@outer }), though extracting the inner loop into a helper function with an early return is usually easier to read and test.
Practice
Practice expression-oriented branching and ranges with these small exercises:
- Write a
whenexpression that maps an HTTP status code (200..299,400..499,500..599) to a status label. - Iterate backward from
10down to2by steps of2usingdownToandstep. - Refactor a nested loop that uses a labeled
break@outerinto a small function with an earlyreturn.