Skip to content
Loops
step 1/5

Reading — step 1 of 5

Learn

~1 min readControl Flow

Kotlin's loop keywords:

for (i in 1..5) println(i)        // 1 2 3 4 5
for (i in 1 until 5) println(i)    // 1 2 3 4 (exclusive upper)
for (i in 5 downTo 1) println(i)   // 5 4 3 2 1
for (i in 0..10 step 2) println(i) // 0 2 4 6 8 10

for (item in list) println(item)
for ((i, item) in list.withIndex()) println("$i: $item")

while and do-while work as expected.

For functional iteration, Kotlin has the standard collection methods:

listOf(1, 2, 3).map { it * 2 }     // [2, 4, 6]
listOf(1, 2, 3).filter { it > 1 }   // [2, 3]
listOf(1, 2, 3).fold(0) { acc, n -> acc + n }   // 6
listOf(1, 2, 3).sum()               // 6

it is the implicit name for a single-parameter lambda. Use named params ({ x -> ... }) for clarity in nested blocks.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…