typestar

Ranges and loops in Kotlin

Ranges are values, and for iterates anything that provides one.

fun main() {
    // Ranges are values: 1..5 includes both ends; downTo and step
    // reshape the walk without an index variable in sight.
    for (km in 1..5) print("$km ")
    println()
    for (switchback in 10 downTo 6) print("$switchback ")
    println()
    for (marker in 0..20 step 5) print("$marker ")
    println()

    var water = 3
    while (water > 0) {
        water -= 1
    }
    println("Bottles left: $water")
}

How it works

  1. 1..5 includes both ends; the loop variable needs no declaration.
  2. 10 downTo 6 runs backward and 0..20 step 5 skips.
  3. while is the classic guard loop for the cases ranges cannot express.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
375
Tokens
90
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 3 of 3 in Control flow, step 6 of 27 in Language basics.

← Previous Next →

Ranges and loops in other languages