LEVIATHAN v962456e · 962456eee1

Standard Library

interface IIterator<T>

The pull protocol for walking a sequence one value at a time.

since 0.1.0-alpha.1linuxwindowswasm

Overview

An iterator answers hasNext to say whether another value is available and returns it from next. Callers must check hasNext before every next; what next does past the end is up to the implementation, and the standard iterators throw. A for loop over an IIterable uses this protocol, so a class that implements IIterator<T> and hands one out from iterator() can be used with for.

Examples

A user-written iterator

class Countdown : IIterator<int> {
    int n;
    new Countdown(int start) { n = start; }
    bool hasNext() => n > 0;
    int next() {
        int v = n;
        n = n - 1;
        return v;
    }
}
Countdown it = Countdown(3);
while (it.hasNext()) {
    console.writeln(it.next());
}
3
2
1

Methods

hasNext

hasNext() -> bool

Test whether another value is available.

Call this before every next. It does not advance the iterator, so it can be called repeatedly.

Returns

true if next can produce a value.

Examples

class Digits : IIterator<int> {
    int i;
    new Digits() { i = 0; }
    bool hasNext() => i < 3;
    int next() {
        int v = i;
        i = i + 1;
        return v;
    }
}
Digits d = Digits();
console.writeln(d.hasNext());
console.writeln(d.hasNext());
d.next();
d.next();
d.next();
console.writeln(d.hasNext());
true
true
false

See also: next

next

next() -> T

Return the next value and move past it.

Only call it when hasNext has returned true. What happens after the last value is not defined by the protocol; the iterators of the standard library throw a RuntimeException, and a user-written one should do the same rather than return a made-up value.

Returns

The next value of the sequence.

Examples

class Evens : IIterator<int> {
    int cur;
    int last;
    new Evens(int last) { cur = 0; this.last = last; }
    bool hasNext() => cur <= last;
    int next() {
        if (cur > last) {
            throw RuntimeException("no more values");
        }
        int v = cur;
        cur = cur + 2;
        return v;
    }
}
Evens e = Evens(4);
console.writeln(e.next());
console.writeln(e.next());
console.writeln(e.next());
try {
    console.writeln(e.next());
} catch (RuntimeException ex) {
    console.writeln("caught: ${ex.message}");
}
0
2
4
caught: no more values

See also: hasNext

See also

  • IIterable — A source of values that can be walked with for.