E07840: it does not have compatible iterator() - hasNext()/next() methods
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:
- An 'iterator()' method that returns an 'Iterator of' its element type
- Or 'hasNext()' (returning a Boolean) AND 'next()' (returning the element) itself - a duck-typed iterator
How to fix it
- Add 'iterator()' returning an 'Iterator of' the element type - often the iterator of a List the type holds ('items.iterator()')
- Or give the type both 'hasNext()' and 'next()'
- 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
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: