liveBook · Manning

Loop

As explained in Kotlin in Action, 2E

A loop is a control structure that repeatedly executes a block of code according to a condition or over a sequence of values.

Loops repeat work: while and do-while run according to a condition, while Kotlin’s idiomatic for form visits values supplied by an iterable. The usual shape is `for (item in elements)`, which runs once per element and makes that element available through the loop variable. section 2.4 section 2.4.3

Use `for` for collections, maps, and numeric progressions. Unlike Java’s classical C-style loop with initialization, condition, and update clauses, Kotlin replaces common counting-loop cases with ranges and progressions. `1..5` includes both endpoints; `1..<5` excludes the endpoint. `downTo` reverses direction, and `step` skips values. section 2.6 section 2.4.2

Listing 2.25 Initializing and iterating over a map
fun main() {
    val binaryReps = mutableMapOf<Char, String>()      #1
    for (char in 'A'..'F') {                           #2
        val binary = char.code.toString(radix = 2)     #3
        binaryReps[char] = binary                      #4
    }
 
    for ((letter, binary) in binaryReps) {             #5
        println("$letter = $binary")
    }
    // A = 1000001    D = 1000100
    // B = 1000010    E = 1000101
    // C = 1000011    F = 1000110
    // (output split into columns for conciseness)
}

This example builds a binary lookup map by looping through the character range `A` through `F`, then iterates over map entries. Destructuring `(letter, binary)` separates each key-value pair directly in the loop header. section 2.4.3

Common loop patterns include:

  • Iterate through a collection with `for (color in collection)` when each item is needed in turn. section 2.4.3
  • Iterate through a map with destructuring, such as `for ((key, value) in map)`. section 2.4.3
  • Keep an index without manual incrementing by iterating over `list.withIndex()` and destructuring the index and element. section 2.4.3
  • Use `while` or `do-while` for condition-controlled repetition; use `break`, `continue`, and labels when nested-loop control requires it. section 2.4.1

`forEach` is a collection function that invokes a lambda for every element. It can be more concise than a regular `for` loop, but is not automatically preferable; use it where the lambda reads clearly. A lambda may also access and modify variables from its surrounding scope. section 5.1.4

How Kotlin in Action, 2E covers it

How deep it goes
Explains loop forms through ranges, map destructuring, indexing, and nested-loop labels; defers destructuring details.
Examples
Demonstrates color collections, binary character maps, indexed lists, Fizz-Buzz, and reverse stepped counting.
What it assumes
Assumes familiarity with Java-like iteration while introducing Kotlin loop forms and range-based counting.
What you can do after
Apply it via Kotlin loop syntax to traverse collections, maps, and numeric ranges without manual index updates.
How it connects
Connects loops with ranges, progressions, maps, destructuring, collections, lambdas, and forEach.

Also explained in

Compare how 27 books explain loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.