CodeGym /Courses /Kotlin SELF /Iterable and Iterator: what’s behind for ( x in colle...

Iterable and Iterator: what’s behind for ( x in collection)

Kotlin SELF
Level 20, Lesson 0
Available

1. How for works under the hood

If you’re just starting to program, for (x in collection) can look like a magic spell from a spellbook: say the words—and elements just flow into your hands. And yes, it really is convenient. But as soon as you want to do something slightly more complex—like “iterate through a collection in a special way”, “stop halfway”, “skip some elements”, or “explain a weird runtime error”—there’s too much magic, and it starts biting.

Good news: there’s no real magic there. In Kotlin, for relies on a simple idea: an object can be iterated if it can provide an iterator. An iterator is like a “remote control for iteration”: it knows whether there is a next element and can return it.

Iterable and Iterator: the basic roles

When you see for (x in something) in code, Kotlin has to understand: “OK, but how do I iterate over this something?” The mechanism is built on two entities:

  • Iterable<T> is the contract “you can iterate over me”.
  • Iterator<T> is the object that performs the iteration right now.

It helps to keep a simple picture in mind: the collection/source provides an iterator, and the iterator “walks” over the elements.

flowchart LR
    A["Iterable⟨T⟩
(data/source)"] -->|"iterator()"| B["Iterator⟨T⟩
(iteration process)"] B -->|"next()"| C["T (next element)"]

Iterable<T>: “a promise that I can be iterated”

In the Kotlin standard library there is an interface Iterable<T>. It is not a “data container” and not a “list”, but rather a contract: the object promises that you can walk through it step by step, getting elements.

Formally, the contract is very simple: Iterable<T> must be able to return an Iterator<T> via the iterator() function.

To simplify the model:

  • Iterable<T> is an “object that can be iterated”.
  • Iterator<T> is a “device that performs iteration right now”.

Iterator<T>: two steps—hasNext() and next()

An iterator stores the “current position” of iteration and can move forward. It has two basic methods:

  • hasNext(): answers the question “are there more elements?”
  • next(): returns the next element and moves the position forward

It sounds dry, but in practice it’s just like a line at a coffee shop: while there are people (hasNext()), you can take the next one (next()), serve them—and the line moves.

Mini example: get an iterator from a list and print the elements.

fun main() {
    val names = listOf("Ann", "Bob", "Cate")
    val it = names.iterator()

    while (it.hasNext()) {
        val name = it.next()
        println(name) // Ann, then Bob, then Cate
    }
}

Yes, this looks longer than for. And yes, that’s exactly why for exists.

The iterator is one-time use: why you can’t “rewind”

When you watch a movie on a streaming service, you can rewind. When you use an iterator, it’s as if you’re watching live TV: frames are gone, and the iterator isn’t required to be able to go back. This is an important concept that often surprises beginners.

Let’s show it in code:

fun main() {
    val nums = listOf(1, 2, 3)
    val it = nums.iterator()

    while (it.hasNext()) {
        print(it.next())
    }
    println() // 123

    // Second attempt with the same iterator:
    println(it.hasNext()) // false
}

Notice: nums didn’t “disappear”; what disappeared is the ability of this particular iterator to continue iterating, because it has already reached the end.

Collection vs iterator: who stores data and who stores “progress”

It’s easy to get confused here, so let’s lock in the model. The collection is the data. The iterator is the “iteration cursor”.

A small table (it’s genuinely worth rereading twice):

Entity What it is What it stores What it can do
Iterable<T> / collection source of elements the elements themselves provide an iterator
Iterator<T> iteration process the current position hasNext() and next()

Quick comprehension check: if you need to repeat the iteration, you create a new iterator, but use the same collection.

3. How for (x in collection) works

The key idea: for in Kotlin is not a separate “special mode”. It’s convenient syntax that performs the exact same iteration, just without the routine.

Let’s compare two variants (both correct). The “human” version:

fun main() {
    val names = listOf("Ann", "Bob", "Cate")
    for (name in names) {
        println(name)
        // Ann
        // Bob
        // Cate
    }
}

And the “mechanical”, but honest one:

fun main() {
    val names = listOf("Ann", "Bob", "Cate")
    val it = names.iterator()

    while (it.hasNext()) {
        val name = it.next()
        println(name)
        // Ann
        // Bob
        // Cate
    }
}

If you understand this equivalence, you’ll stop treating for as magic. It’s like an autopilot: you don’t have to turn the steering wheel by hand every time, but it’s useful to know the steering wheel exists.

The “for equivalent” as a cheat sheet for reading code

Sometimes you read someone else’s code and see: “Whoa, there’s a manual iterator, while, hasNext()... what’s going on?” To avoid getting lost, keep a simple cheat sheet in mind:

for (x in collection) {
    body(x)
}

mentally turns into:

val it = collection.iterator()
while (it.hasNext()) {
    val x = it.next()
    body(x)
}

This is not necessarily the literal same bytecode in every situation, but as a mental model it works great.

4. Practice: SimplePlanner and printing tasks

Let’s continue developing our console app (let’s call it SimplePlanner): it stores a list of task strings in a MutableList<String>. Today we won’t build the entire command interface, but we’ll add one useful function: print all tasks.

Printing tasks “manually”, via an iterator

Why via an iterator? Not because you always need to, but so you can see the mechanics and stop being afraid of them.

fun printTasksManual(tasks: List<String>) {
    val it = tasks.iterator()
    var number = 1

    while (it.hasNext()) {
        val task = it.next()
        println("${number}. $task") // 1. ..., 2. ...
        number++
    }
}

Let’s test it in main:

fun main() {
    val tasks = mutableListOf("Buy milk", "Read Kotlin docs", "Sleep")
    printTasksManual(tasks)
    // 1. Buy milk
    // 2. Read Kotlin docs
    // 3. Sleep
}

Yes, this is a bit longer than for ((i, task) in tasks.withIndex()). But our goal right now is to see the “engine”, not just the nice bodywork.

The same meaning, but shorter: for as the default style

After you’ve seen the “engine”, you can safely go back to normal syntax. In most cases, for is the best option: it’s shorter, more readable, and gives you fewer chances to make a mistake (for example, forgetting hasNext() and calling next() into the void).

Printing tasks code will usually look like this:

fun printTasks(tasks: List<String>) {
    var number = 1
    for (task in tasks) {
        println("${number}. $task") // 1. ..., 2. ...
        number++
    }
}

The meaning is the same, but it reads easier.

5. When you need an explicit iterator and what to remember

In your first steps in programming, you can go for years without a manual iterator and feel perfectly fine. But sometimes manual control over iteration is useful: you want to control steps, stop based on a condition, or perform a special operation during iteration without turning for into a mess.

Another common scenario is carefully modifying a mutable collection during iteration (but that’s a separate topic; here we’re only laying the foundation, without details).

How Kotlin knows an object can be used in for

Kotlin doesn’t guess—it looks for the “right shape”.

An object can be used in for (x in obj) if Kotlin can obtain an iterator from it. In practice, this boils down to the rule: the object must have an iterator() function, and the returned iterator must have hasNext() and next() methods.

For today it’s enough to remember:

  • List, Set, Map (via entries, keys, values) and many other standard collections are already “iterable”—you can use them in for right away.
  • If you create your own class, it won’t become “iterable” by itself until it supports iterator().

6. Typical mistakes when working with Iterable and Iterator

Mistake #1: confusing a collection and an iterator (“I took an iterator—where are my elements?”).
A collection is a storage of elements, an iterator is a temporary object that indicates “where we are now” in iteration. An iterator doesn’t have to be able to do everything a collection can: you won’t ask it for size, you won’t “rewind” it, and you won’t expect it to live forever. It often helps to say it out loud: “collection = data, iterator = process”.

Mistake #2: calling next() without checking hasNext().
In manual iteration with while there is an iron rule: first ask “is there a next one?”, then take the next one. If you call next() on an iterator that is already exhausted, you’ll get a runtime exception (that is, the program will crash). for protects you from this mistake automatically, so the manual style requires more discipline.

Mistake #3: expecting to reuse an iterator (“I’ll just iterate once more with the same it”).
An iterator is one-time use. If you’ve reached the end, hasNext() will be false, and you won’t be able to “repeat” the iteration. You need to call collection.iterator() again and get a new iterator.

Mistake #4: treating for as “language magic” that can’t be explained.
for is syntactic convenience. It simply hides the iterator routine from you. Once you understand that for is based on iterator()/hasNext()/next(), the code becomes more predictable: you read other people’s solutions more easily, find the causes of errors faster, and more calmly move on to more complex iteration scenarios.

Mistake #5: using a manual iterator where a normal for is needed.
A manual iterator is not “more professional”. It’s just a tool. If you don’t need special logic to control iteration, then for will be shorter, safer, and clearer. In programming, there are many places where “shorter and clearer” is not laziness—it’s quality.

1
Task
Kotlin SELF, level 20, lesson 0
Locked
Travel itinerary
Travel itinerary
1
Task
Kotlin SELF, level 20, lesson 0
Locked
To-do list
To-do list
1
Task
Kotlin SELF, level 20, lesson 0
Locked
A Mood Boost
A Mood Boost
1
Task
Kotlin SELF, level 20, lesson 0
Locked
Prefix search
Prefix search
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION