Control Flow: if, when & loops
Control flow decides what runs
Programs need to make decisions (“if the user is logged in, show the dashboard”) and repeat work (“for each item, draw a row”). Kotlin’s control-flow tools are familiar but more powerful than in many languages, because most of them are expressions — they return a value.
if as an expression
In Kotlin, if can return a value, so you rarely need a separate ternary operator:
val a = 7
val b = 12
val max = if (a > b) a else b // max gets 12
// it can span multiple lines too
val label = if (max > 10) {
"big"
} else {
"small"
}
when: a supercharged switch
when replaces long if-else chains and is far more flexible — it can match values, ranges, types and conditions.
val score = 82
val grade = when (score) {
in 90..100 -> "A"
in 75..89 -> "B"
in 50..74 -> "C"
else -> "Fail"
}
// when without an argument acts like if-else
val status = when {
score >= 50 -> "Pass"
else -> "Retry"
}
Example — matching types:
fun describe(x: Any): String = when (x) {
is Int -> "a number: $x"
is String -> "text of length ${x.length}"
else -> "something else"
}
Loops
// ranges
for (i in 1..5) print(i) // 12345
for (i in 5 downTo 1) print(i) // 54321
for (i in 0..10 step 2) print(i) // 0246810
for (i in 1 until 5) print(i) // 1234 (excludes 5)
// iterate a collection
val fruits = listOf("apple", "mango", "kiwi")
for (fruit in fruits) println(fruit)
// with index
for ((index, fruit) in fruits.withIndex()) {
println("$index: $fruit")
}
while and do-while
var n = 3
while (n > 0) { println(n); n-- }
do { println("runs at least once") } while (false)
break and continue
for (i in 1..10) {
if (i == 3) continue // skip 3
if (i == 6) break // stop at 6
print(i) // 1245
}
Common mistakes
- Writing long if-else ladders instead of a clean
when. - Using
..when you meanuntil(off-by-one errors on list indices). - Forgetting that
if/whenreturn values — you can assign them directly.
Summary: Useif/whenas expressions to assign values directly, and prefer ranges (1..n,until,step) for clean, readable loops.