Chapter 24: the third safe container, built
Optional and Result are not the only containers the compiler polices: an Iterator is the third. next() without a hasNext() is the same error as a bare get(). This program reads one iterator in a while loop and another, empty one, in an if. The IDE writes the program's shell; you type the two reads. To play it in the IDE: Help > Lessons > EK9 in Depth…, or ek9 -ide -lesson depth-iteration.
What you'll build
The lesson builds this program from a file holding only its module line - the finished file, as the book prints it.
#!ek9 defines module book.iteration defines program Iteration() stdout <- Stdout() colours <- ["red", "green", "blue"] cursor <- colours.iterator() while cursor.hasNext() stdout.println(cursor.next()) noColours <- List() of String emptyCursor <- noColours.iterator() if emptyCursor.hasNext() stdout.println(emptyCursor.next()) else stdout.println("nothing to read")
Step 1: The program
Choose Code > New Construct > Program…
Iteration is the program's name. Choose Preview.
The preview shows Iteration about to be written. Choose Apply.
Select the Iteration() line and, above it, type the blank line the book opens the program with. Saves when typed.
Select the stub, from ready <- true down to its //AI line, and type Iteration's body exactly as the chapter shows it. Saves when typed.
Step 2: Run it
Choose Run > Run Program…
The project's only program is already chosen. Choose Run.
red, green, blue, then nothing to read - the empty iterator never reached next(). Choose Close.
The result
Iteration.ek9 now reads exactly as chapter 24 of EK9 in Depth shows it. Each next() sits inside the hasNext() that proves it - the loop's head, and the if's - so the empty iterator reaches the else.
Where this lesson comes from
- For AI assistants - the MCP tool
ek9_add_program.








