E07840: it does not have compatible iterator() - hasNext()/next() methods

Category: E07xxx Full resolution · Reported in phase: FULL_RESOLUTION · Classification: MISSING_ITERATE_METHOD · All error codes

What went wrong

You're trying to iterate over a type with 'cat' but it doesn't implement the required iterator methods.

Worked examples

Compilable examples demonstrating this error and the correct fix:

  • ek9 -q 85 (How do I use Optional in stream pipelines?)

[EK9 ITERATION PATTERN] To make a type iterable with 'cat' or 'for', it needs either:

  1. An 'iterator()' method that returns an 'Iterator of' its element type
  2. Or 'hasNext()' (returning a Boolean) AND 'next()' (returning the element) itself - a duck-typed iterator

How to fix it

  1. Add 'iterator()' returning an 'Iterator of' the element type - often the iterator of a List the type holds ('items.iterator()')
  2. Or give the type both 'hasNext()' and 'next()'
  3. Or use built-in iterable types (List, Dict, etc.)

The [EXAMPLE] section below shows a type with 'hasNext()' and no 'next()', and the same type with both.

See also

  • E07840: missing iterator for cat (this error)
  • E07830: missing pipe operator for collect

Examples

Every example is compiled by the EK9 compiler: the first fails exactly as captioned, the others fix it.

Fails with E07840: it does not have compatible iterator() - hasNext()/next() methods

#!ek9
defines module error.e07840.bad

  defines class

    Countdown
      hasNext()
        <- rtn as Boolean: false

  defines function

    printAll()
      stdout <- Stdout()

      //A for loop needs next() as well as hasNext()
      for step in Countdown()
        stdout.println("step")

Fixed: Provide both hasNext() and next()

#!ek9
defines module error.e07840.good

  defines class

    Countdown
      remaining <- 3

      hasNext()
        <- rtn as Boolean: remaining > 0

      next()
        <- rtn as Integer: Integer(remaining)
        remaining--

      default operator ?

  defines program

    PrintAll()
      stdout <- Stdout()

      //hasNext() and next(): a duck-typed iterator
      for step in Countdown()
        stdout.println($step)

Questions and answers

These Q&A entries show E07840 and its fix: