for, while and the Iterator Protocol

for, while and the Iterator Protocol in Kotlin: At the head of a sawmill's bandsaw there is a log deck: a sloped steel table, wide enough for a dozen logs,…

The Analogy: The Bandsaw Log Deck and the Kicker Arm

At the head of a sawmill's bandsaw there is a log deck: a sloped steel table, wide enough for a dozen logs, that feeds the saw carriage. The logs lie across it side by side, and they do not roll onto the carriage by themselves. A hydraulic kicker arm lies flush in a slot along the low edge of the deck, and when the sawyer taps a pedal the arm rises, lifts the nearest log over the lip, and drops it onto the carriage. Then the arm falls back into its slot and waits. One tap, one log.

Two quite separate pieces of ironmongery make that work, and the distinction is the whole of this lesson. The first is a limit switch at the low edge of the deck: a sprung paddle that a log's weight holds down, wired to a lamp on the sawyer's post. Lamp lit, there is a log against the lip. Lamp dark, there is not. The switch only ever answers a question -- it never moves anything. The second is the kicker arm itself, which never asks a question -- it strokes when the pedal is tapped and lifts whatever happens to be there. A sawyer who taps the pedal with the lamp dark gets a full stroke of the arm into thin air and a carriage that travels the length of the saw with nothing on it.

There are two ways to work a shift, and every mill runs both. The first is by ticket: the foreman hands down a docket saying twelve logs from the oak stack, and the sawyer strokes twelve times, counting. The count comes from the paper, not from the deck. The second is by the lamp: keep tapping while the lamp is lit, and stop when it goes dark. The count comes from the deck, and the sawyer does not know it in advance. A third arrangement exists for the first stroke of the morning, when the arm is dropped once before anybody looks at the lamp, because the night crew always leaves one log loaded and checking first would waste a stroke.

The failure mode is the gap between the lamp and the pedal. A yardman with a loader is topping the deck up from the far side while the sawyer works the near side, and there is a second or two between the sawyer glancing at the lamp and the arm completing its stroke. If a log is dragged off in that gap, the arm strokes into air. If two are pushed on, the count on the docket no longer matches the logs that went through, and the tally sheet at the end of the shift is wrong with no single stroke to blame. Every mill has the same rule pinned to the post: nobody touches the deck while the arm is working. In Kotlin that rule is enforced for you, loudly, by ConcurrentModificationException -- and, in one specific case, not enforced at all.


Syntax or Core Structure

A for loop in Kotlin has no counter, no condition and no increment. It has a name, the word in, and something to walk. Everything else -- while, do while, repeat -- is a way of driving the loop from a condition instead of from a collection.

class Deck(private val logs: List<Int>) : Iterable<Int> {
    override fun iterator(): Iterator<Int> = logs.iterator()
    val size: Int get() = logs.size
}

fun main() {
    val deck = Deck(listOf(220, 180, 310, 95))

    var total = 0
    for (log in deck) total += log
    println("logs " + deck.size + " total " + total + " cm")

    val arm = deck.iterator()
    var strokes = 0
    while (arm.hasNext()) {
        val log = arm.next()
        strokes++
        println("stroke " + strokes + " takes " + log + " cm")
    }

    var remaining = total
    var passes = 0
    do {
        remaining -= 250
        passes++
    } while (remaining > 0)
    println("passes " + passes + " overrun " + (-remaining) + " cm")

    repeat(3) { i -> println("blade check " + (i + 1)) }
}

Output:

logs 4 total 805 cm
stroke 1 takes 220 cm
stroke 2 takes 180 cm
stroke 3 takes 310 cm
stroke 4 takes 95 cm
passes 4 overrun 195 cm
blade check 1
blade check 2
blade check 3

The for loop and the while loop below it walk the same four logs and produce the same four numbers, because the for loop is the while loop: the compiler asks deck for an iterator, calls hasNext() before each pass and next() to get the value. Writing it out by hand, as the arm block does, buys you nothing here -- but it is the version you must be able to picture, because every surprise in this topic comes from those two calls being separate. The do while block is the morning stroke: remaining starts at 805, four subtractions of 250 take it to -195, and the condition is only consulted after the body has run, which is why passes is 4 and not 3. repeat(3) is the docket: the count comes from the number you wrote, and the lambda receives the index, zero-based, which is why the printed checks add one.


Technical Depth: What for Actually Requires

Kotlin's for is defined by convention, not by type. The right-hand side of in needs a function called iterator() -- a member or an extension, marked operator -- that returns something with a hasNext(): Boolean and a next(). It does not need to be an Iterable, it does not need to implement any interface, and in several common cases no iterator object is created at all because the compiler recognises the shape and emits a plain index loop.

Loop written asWhat the compiler usesAllocates an iterator
for (x in list)the iterator() member of Iterableyes
for (x in 1..10)the range's ends, compiled to an index loopno
for (x in array)the array's size and index accessno
for (c in "text")the iterator() extension on CharSequenceyes
for ((k, v) in map)Map.iterator() plus component1 and component2yes
for (i in list.indices)an IntRange, so an index loopno
for (x in myType)an operator fun iterator() you wrote yourselfup to you

The second and sixth rows are why for (i in 0 until n) costs nothing in Kotlin. A range used directly as a loop subject is erased at compile time; the same range stored in a val of type Iterable<Int> is not, because the compiler can no longer see that it is a range.

FormBody runsReach for it when
for (x in xs)once per elementyou are walking something
while (c)zero or more timesthe count comes from a condition
do ... while (c)one or more timesthe first pass is unconditional
repeat(n) { }exactly n timesthe count is a number you already have
xs.forEach { }once per elementyou are chaining, and never need break

The protocol by hand, and making your own type walkable

class Kicker(private val deckLengths: IntArray) {
    val count: Int get() = deckLengths.size
    fun lengthAt(i: Int): Int = deckLengths[i]
}

operator fun Kicker.iterator(): Iterator<Int> = object : Iterator<Int> {
    private var i = 0
    override fun hasNext(): Boolean = i < count
    override fun next(): Int = lengthAt(i++)
}

class Countdown(private val from: Int) : Iterable<Int> {
    override fun iterator(): Iterator<Int> = object : Iterator<Int> {
        private var n = from
        override fun hasNext(): Boolean = n > 0
        override fun next(): Int {
            if (!hasNext()) throw NoSuchElementException("countdown exhausted")
            return n--
        }
    }
}

fun main() {
    val kicker = Kicker(intArrayOf(220, 180, 310))
    var sum = 0
    for (len in kicker) sum += len
    println("kicker count " + kicker.count + " sum " + sum)

    println("countdown: " + Countdown(4).joinToString(" "))
    println("twice: " + Countdown(3).joinToString(" ") + " / " + Countdown(3).joinToString(" "))

    val one = Countdown(2).iterator()
    val h1 = one.hasNext()
    val v1 = one.next()
    val v2 = one.next()
    val h2 = one.hasNext()
    println("by hand: hasNext " + h1 + " -> " + v1 + " -> " + v2 + " hasNext " + h2)

    var caught = "none"
    try {
        one.next()
    } catch (e: NoSuchElementException) {
        caught = e.message ?: "no message"
    }
    println("after the end: " + caught)
}

Output:

kicker count 3 sum 710
countdown: 4 3 2 1
twice: 3 2 1 / 3 2 1
by hand: hasNext true -> 2 -> 1 hasNext false
after the end: countdown exhausted

Kicker implements nothing at all -- no interface, no supertype -- and yet for (len in kicker) compiles, because the operator fun Kicker.iterator() extension satisfies the convention. That is the escape hatch for types you do not own. Countdown takes the other route and implements Iterable<Int>, which costs one method and buys the whole of the collection extension library: joinToString on line two is not something Countdown wrote. The third line matters more than it looks -- calling iterator() twice gives two independent walks, because Countdown.iterator() builds a fresh object each time. An Iterable that returns the same iterator twice is a bug that shows up as a second loop mysteriously doing nothing. The last two lines are the lamp and the pedal: hasNext() reports honestly, next() past the end throws NoSuchElementException, and an iterator that omits that check simply returns nonsense instead.

Maps, indices, and the walk you must not disturb

fun main() {
    val order = listOf("OAK", "ASH", "ELM")
    val lengths = linkedMapOf("OAK" to 220, "ASH" to 180, "ELM" to 310)

    for ((wood, cm) in lengths) println("wood " + wood + " needs " + cm + " cm")
    for (i in order.indices) println("slot " + i + " holds " + order[i])
    for ((i, wood) in order.withIndex()) println("index " + i + " is " + wood)

    val deck = mutableListOf(220, 180, 310, 95)
    var deckVisits = 0
    var deckResult = "no exception"
    try {
        for (log in deck) {
            deckVisits++
            if (log < 100) deck.remove(log)
        }
    } catch (e: ConcurrentModificationException) {
        deckResult = "ConcurrentModificationException"
    }
    println("removed the last: " + deckResult +
        " visits " + deckVisits + " left " + deck.size)

    val quiet = mutableListOf(220, 180, 95, 310)
    var quietVisits = 0
    var quietResult = "no exception"
    try {
        for (log in quiet) {
            quietVisits++
            if (log < 100) quiet.remove(log)
        }
    } catch (e: ConcurrentModificationException) {
        quietResult = "ConcurrentModificationException"
    }
    println("removed the one before last: " + quietResult +
        " visits " + quietVisits + " left " + quiet.size)

    val safe = mutableListOf(220, 180, 95, 310)
    safe.removeAll { it < 100 }
    println("removeAll instead: " + safe.joinToString(" ") + " left " + safe.size)
}

Output:

wood OAK needs 220 cm
wood ASH needs 180 cm
wood ELM needs 310 cm
slot 0 holds OAK
slot 1 holds ASH
slot 2 holds ELM
index 0 is OAK
index 1 is ASH
index 2 is ELM
removed the last: ConcurrentModificationException visits 4 left 3
removed the one before last: no exception visits 3 left 3
removeAll instead: 220 180 310 left 3

The map loop destructures each entry into two names, which works because Map.Entry has component1 and component2 extensions; linkedMapOf is used rather than mapOf so the order of those three lines is the order they were written and not a hash order. The two middle loops are the same walk expressed twice, and withIndex() is the one to prefer when you need both the position and the value, because order[i] re-indexes on every pass.

The last three lines are the yardman and the loader, and they deserve to be read twice. Both mutating loops remove exactly one element from a list of four; the only difference is where that element sits. Removing the last one leaves the iterator's cursor at 4 while the list's size drops to 3, so hasNext() -- which on a JVM ArrayList is cursor != size -- says true, next() performs its fail-fast check and throws, and the visit count of 4 tells you the loop did complete a pass over every original element. Removing the one before last leaves the cursor at 3 and the size at 3, so hasNext() says false, the loop exits with no complaint whatsoever, and the visit count of 3 is the tell: ELM's 310 was never looked at. That silent case is the one that reaches production. Both are the JVM collection's fail-fast contract rather than a Kotlin language guarantee, and the honest fix is the last line -- removeAll with a predicate mutates the list from the outside, once, with no walk to invalidate.


Real World Example: Breaking Down a Log Deck into Boards

const val LOGS = "OAK:220,ASH:180,ELM:310,BEECH:95,PINE:265"

val BOARDS = listOf(120, 80, 50)

const val W_LOG = 8
const val W_RAW = 6
const val W_PLAN = 13
const val W_COUNT = 8
const val W_CUT = 6
const val W_WASTE = 7

fun row(log: String, raw: String, plan: String, count: String,
        cut: String, waste: String): String =
    log.padStart(W_LOG) + raw.padStart(W_RAW) + plan.padStart(W_PLAN) +
        count.padStart(W_COUNT) + cut.padStart(W_CUT) + waste.padStart(W_WASTE)

fun main() {
    val width = W_LOG + W_RAW + W_PLAN + W_COUNT + W_CUT + W_WASTE
    val records = LOGS.split(",")
    val tally = IntArray(BOARDS.size)
    var totalRaw = 0
    var totalCut = 0
    var totalWaste = 0
    var totalBoards = 0

    println(row("LOG", "RAW", "PLAN", "BOARDS", "CUT", "WASTE"))
    println("-".repeat(width))

    for (record in records) {
        val parts = record.split(":")
        val name = parts[0]
        val raw = parts[1].toInt()
        val plan = mutableListOf<Int>()
        var remaining = raw

        while (true) {
            var chosen = -1
            for (i in BOARDS.indices) {
                if (BOARDS[i] <= remaining) {
                    chosen = i
                    break
                }
            }
            if (chosen < 0) break
            plan.add(BOARDS[chosen])
            tally[chosen]++
            remaining -= BOARDS[chosen]
        }

        val cut = raw - remaining
        totalRaw += raw
        totalCut += cut
        totalWaste += remaining
        totalBoards += plan.size

        println(row(name, raw.toString(), plan.joinToString("+"),
            plan.size.toString(), cut.toString(), remaining.toString()))
    }

    println("-".repeat(width))
    println(row("TOTALS", totalRaw.toString(), "--", totalBoards.toString(),
        totalCut.toString(), totalWaste.toString()))

    var bySize = 0
    for (i in BOARDS.indices) bySize += BOARDS[i] * tally[i]

    println("boards: " + BOARDS.mapIndexed { i, b -> b.toString() + "=" + tally[i] }
        .joinToString(" "))
    println("cut " + totalCut + " + waste " + totalWaste +
        " = " + (totalCut + totalWaste) +
        " agree: " + (totalCut + totalWaste == totalRaw))
    println("by size: " + BOARDS.mapIndexed { i, b -> tally[i].toString() + "*" + b }
        .joinToString(" + ") + " = " + bySize + " agree: " + (bySize == totalCut))
    println("yield " + (totalCut * 100 / totalRaw) + " percent by integer division")
}

Output:

     LOG   RAW         PLAN  BOARDS   CUT  WASTE
------------------------------------------------
     OAK   220       120+80       2   200     20
     ASH   180       120+50       2   170     10
     ELM   310   120+120+50       3   290     20
   BEECH    95           80       1    80     15
    PINE   265      120+120       2   240     25
------------------------------------------------
  TOTALS  1070           --      10   980     90
boards: 120=6 80=2 50=2
cut 980 + waste 90 = 1070 agree: true
by size: 6*120 + 2*80 + 2*50 = 980 agree: true
yield 91 percent by integer division

Three loops are stacked here and each one is a different tool. The outer for (record in records) walks a collection, so the count comes from the data. The while (true) inside it breaks a single log down, and its count is genuinely unknown before it runs -- a 95 cm log yields one board and a 310 cm log yields three, and no docket could have said so in advance. The innermost for (i in BOARDS.indices) is not walking anything at all; it is searching, and its break means "stop at the first board that fits". Three loops, three reasons, and the choice of form in each case is forced by where the count comes from.

Follow ELM along its row to see the middle loop work. It starts at 310, takes a 120 leaving 190, takes another 120 leaving 70, takes a 50 leaving 20, and then the inner search finds nothing at or under 20, sets chosen to -1 and the outer break fires. plan holds three boards, cut is 310 minus 20, and the PLAN cell is those three numbers joined with a plus. Every other row is the same walk with different numbers, and BEECH shows the search skipping a board it cannot use: 95 is under 120, so the first iteration of the inner for does not match and the second one does.

The bottom four lines are the mill's tally. tally is an IntArray indexed by position in BOARDS, so 120=6 80=2 50=2 comes out in the order the sizes were declared rather than in a hash order. The by size line is the useful one: it multiplies the tally by the board sizes and gets 980, which is the CUT column's own total arrived at from completely different numbers, so if a board were tallied under the wrong size the two would part company. The yield is deliberately integer division -- 98000 divided by 1070 is 91 and a bit, and the printed 91 is labelled as such rather than pretending to a precision the arithmetic does not have.

Now the flaw, which the board is quietly hiding. The plan is greedy: take the largest board that fits, subtract, repeat. Look at OAK. It is 220 cm, the mill cut 120 and 80 from it, and threw 20 cm away. But 120 plus 50 plus 50 is exactly 220 -- three boards and no waste at all, from the same log, using the same three sizes. The greedy loop cannot find that, because it commits to the 80 the moment 80 fits and while (true) never reconsiders a board it has already added. PINE is worse: 80 plus 80 plus 50 plus 50 is 260, four boards and 5 cm of waste, against the two boards and 25 cm the greedy plan produced. And nothing on the board says so, because cut + waste = raw is not a check at all -- cut is defined as raw - remaining, so that line is an algebraic identity that will print true no matter how badly the log was cut. The genuine cross-check is the by size line, and it validates the tally, not the plan. Two smaller limits sit beside it. row pads but never truncates, so a 600 cm log would produce a PLAN cell of 120+120+120+120+120, nineteen characters in a thirteen-wide column, and shift every later column right. And tally is positional, which silently requires BOARDS to stay in descending order for the inner break to mean "largest that fits" -- reorder that one list and every plan on the board changes while both reconciliation lines still say true.


Common Mistakes

  1. Reaching for a C-style for. for (i = 0; i < n; i++) is not Kotlin syntax and there is no plan to add it. Write for (i in 0 until n), or for (i in xs.indices), or -- best -- walk the collection and let go of the index entirely.
  1. Mutating a collection inside a for over it. Adding or removing during the walk invalidates the iterator. Use removeAll or retainAll with a predicate, build a new list with filter, or take an explicit MutableIterator and call its own remove().
  1. Reading a clean exit as proof the loop saw everything. On a JVM ArrayList, removing the element one before the last leaves cursor == size, so hasNext() returns false and the loop ends with no exception and one element never inspected. Count your visits if it matters.
  1. Trying to break out of forEach. It does not compile: break belongs to loops, and a lambda is not one. return@forEach behaves like continue, not like break. If you need to stop early, use a for loop, or first, firstOrNull or takeWhile.
  1. Writing an Iterable that returns the same iterator twice. Caching the iterator in a field makes the first loop work and every loop after it do nothing, because the cached cursor is already at the end. iterator() must build a fresh walk on every call.
  1. Calling next() more than once per hasNext(). Every next() advances. A hand-written while (it.hasNext()) whose body consumes two elements will run off the end on an odd-sized collection, and the exception will point at the wrong line.
  1. Using do while where while was meant. The body of a do while runs before the condition is ever consulted, so on an empty subject it executes exactly once with nothing to work on. Reserve it for the case where the first pass genuinely is unconditional.
  1. Keeping a hand-rolled index beside a for. var i = 0 incremented at the bottom of the body drifts the moment a continue appears above it. withIndex() cannot drift, and indices cannot go out of bounds.
  1. Expecting the loop variable to be assignable. for (x in xs) { x = ... } does not compile: each pass binds a fresh read-only x. That freshness is also what makes it safe to capture in a lambda -- each closure holds that pass's value, not a shared slot.

Best Practices

  • Walk the subject itself. for (log in deck) says what you mean; for (i in deck.indices) says it through an index you then have to be trusted with. Reach for the index only when the position is part of the work.
  • When you need both the position and the value, use withIndex() rather than an index plus a subscript. It reads better and it removes the possibility of the two drifting apart.
  • Let the shape of the count choose the form: for when a collection decides how many passes there are, while when a condition does, do while only when the first pass is genuinely unconditional, and repeat(n) when the number is already in your hand.
  • Never mutate a collection you are walking. Build a new one, or mutate it from outside the loop with removeAll, retainAll or replaceAll, all of which do their work in one pass with no iterator to invalidate.
  • In a custom Iterable, return a brand-new iterator from every iterator() call, and make next() throw NoSuchElementException past the end rather than returning a default. A silent default turns a bug into bad data.
  • To make a type you do not own walkable, write an operator fun iterator() extension rather than a wrapper class. It costs three lines, needs no subclassing, and for will accept it.
  • Give while (true) exactly one exit and put the exit condition where a reader looking for it will land -- ideally in a named val or a small function, so the loop reads as a sentence rather than as a puzzle.
  • Prefer a for loop to forEach whenever the body is more than a single expression or might need to stop early. Save forEach for the end of a chain, where the alternative would be an awkward intermediate variable.

Practice Exercises

  1. Replace the greedy plan in the sawmill program with an exhaustive one. For each log, try every combination of the three board sizes that fits and keep the one with the least waste, breaking ties by the greater board count. Print the greedy PLAN and the best PLAN side by side, and report the total waste under each -- OAK should fall from 20 cm to 0.
  1. Rewrite the removal loop using an explicit MutableIterator: take deck.iterator() as a MutableIterator<Int>, walk it with while (it.hasNext()), and call it.remove() instead of deck.remove(log). Confirm no exception is thrown, that every element is visited, and that the resulting list matches what removeAll produces.
  1. Give a Grid(val rows: Int, val cols: Int) class an operator fun iterator() that yields each cell as a Pair<Int, Int> in row-major order, without materialising a list. Walk a 3 by 4 grid with a plain for, print the twelve pairs, and assert the count is rows * cols.
  1. Build a table of the fail-fast behaviour. For list sizes 2 through 8, and for each position in the list, run a for loop that removes the element at that position and record whether it threw ConcurrentModificationException, exited quietly, or completed normally. Print one row per size with a mark per position, and state in one sentence which position is always the quiet one and why.