Control Flow: if, when, Loops and Ranges
Harry
· 23 Sep 2026
· 3 views
Log in to track your progress and mark lessons complete.
Sponsored
if as Expression
val badge = if (score >= 60) "Passed" else "Failed"when (Supercharged Switch)
val msg = when (role) {
"admin" -> "Full access"
"editor", "author" -> "Can publish"
in 1..5 -> "Level $role"
is String -> "Text role"
else -> "Reader"
}when matches values, ranges, types and conditions - and can be used as an expression or statement.
Loops
for (i in 1..5) print(i) // 1 to 5
for (i in 5 downTo 1) print(i) // countdown
for (c in "Kotlin") print(c) // characters
repeat(3) { println("hi") } // no loop variable needed
while (queue.isNotEmpty()) serve()Ranges and Progressions
1..10inclusive,1 until 10excludes end.1..10 step 2,10 downTo 1 step 3.x in 1..10tests membership anywhere.
Key Points
- if and when return values - assign them directly.
- when replaces most switch, instanceof chains and if-ladders.
- Ranges make loops readable and membership checks trivial.