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.

The EK9 IDE as the lesson opens

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…

The EK9 IDE once this is done: Choose Code > New Construct > Program…

Iteration is the program's name. Choose Preview.

The EK9 IDE just before choosing Preview: Iteration is the program's name

The preview shows Iteration about to be written. Choose Apply.

The EK9 IDE just before choosing Apply: The preview shows Iteration about to be written

Select the Iteration() line and, above it, type the blank line the book opens the program with. Saves when typed.

The EK9 IDE once this is done: Select the Iteration() line and, above it, type the blank line the book opens the program with

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.

The EK9 IDE once this is done: Select the stub, from ready <- true down to its //AI line, and type Iteration's body exactly as the chapter shows it

Step 2: Run it

Choose Run > Run Program…

The EK9 IDE once this is done: 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 EK9 IDE just before choosing Close: red, green, blue, then nothing to read - the empty iterator never reached next()

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.

The EK9 IDE when the lesson has finished

Where this lesson comes from