iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

for / while

Kotlin loops are for over an iterable, while, and do-while. The standard library’s sequence operators (map, filter, fold) replace most imperative loops in real code.

for-in + ranges + when-to-not-loop

EXAMPLE
fun main() {
    // 1) for-in — anything iterable
    for (i in 0..4) println(i)         // 0..4 inclusive
    for (i in 0 until 5) println(i)     // 0..4 exclusive
    for (i in 10 downTo 1 step 2) println(i)   // 10, 8, 6, 4, 2

    for (c in "hello") println(c)
    for ((i, c) in "hello".withIndex()) println("$i=$c")

    for ((k, v) in mapOf("Ada" to 36, "Bo" to 28)) println("$k=$v")

    // 2) while + do-while
    var n = 0
    while (n < 5) n++

    do {
        n--
    } while (n > 0)

    // 3) Labels — break / continue outer loops
    outer@ for (i in 1..5) {
        for (j in 1..5) {
            if (j > i)        continue@outer
            if (i * j > 10)   break@outer
            println("$i*$j")
        }
    }

    // 4) repeat — fixed N times
    repeat(5) { i -> println(i) }

    // 5) Functional alternatives — usually beat the manual loop
    val nums = listOf(1, 2, 3, 4, 5)
    val doubled = nums.map { it * 2 }
    val evens   = nums.filter { it % 2 == 0 }
    val sum     = nums.sum()
    val byParity = nums.groupBy { if (it % 2 == 0) "even" else "odd" }
}

Why it matters

Use the functional API by default. Reach for explicit loops when you need break / continue control or when allocation-free traversal matters in a hot loop.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
for (i in 0 until 5) println(i)
for (x in listOf("a","b")) println(x)

var n = 3
while (n > 0) { println(n); n-- }
Try it Yourself »

Discussion

Loading…