Control Flow: if, when, Loops and Ranges

Harry · 23 Sep 2026 · 3 views
Log in to track your progress and mark lessons complete.

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..10 inclusive, 1 until 10 excludes end.
  • 1..10 step 2, 10 downTo 1 step 3.
  • x in 1..10 tests 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.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in