Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Iterable<E>

Tags:

dart

I am trying to port the Java code below to Dart and am puzzled about to do this.

In Java the Iterable interface is where clean with one method and to implement this is a snap.

How is this code best transformed to Dart?

/**
 * Chess squares represented as a bitmap.
 */
public class ChessSquares implements Iterable<ChessSquare> {

private static class ChessSquaresIterator implements Iterator<ChessSquare> {
    long bits;
    int nextBit;

    public ChessSquaresIterator(long bits) {
        this.bits = bits;
        nextBit = Long.numberOfTrailingZeros(bits);
    }

    @Override
    public boolean hasNext() {
        return (nextBit < 64);
    }

    @Override
    public ChessSquare next() {
        ChessSquare sq = ChessSquare.values()[nextBit];
        bits = bits & ~sq.bit;
        nextBit = Long.numberOfTrailingZeros(bits);
        return sq;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}


@Override
public Iterator<ChessSquare> iterator() {
    return new ChessSquaresIterator(bits);
}

...
like image 400
Gunnar Eketrapp Avatar asked Apr 20 '13 05:04

Gunnar Eketrapp


People also ask

How is Iterator implemented?

To implement an Iterator, we need a cursor or pointer to keep track of which element we currently are on. Depending on the underlying data structure, we can progress from one element to another. This is done in the next() method which returns the current element and the cursor advances to next element.

What is Iterable <>?

Connect with your customers like you actually know them. Iterable is a cross-channel marketing platform that powers unified customer experiences and empowers you to create, optimize and measure every interaction across the entire customer journey.

What implements Iterable in Java?

An Iterable interface is defined in java. lang package and introduced with Java 5 version. An object that implements this interface allows it to be the target of the "for-each" statement. This for-each loop is used for iterating over arrays and collections.


1 Answers

By using IterableMixin you only need to implement the iterator-function.

class ChessSquares with IterableMixin<ChessSquare> {
    @override
    Iterator<ChessSquare> get iterator => new ChessSquaresIterator(bits);
    ...
}

Visit http://blog.sethladd.com/2013/03/first-look-at-dart-mixins.html for a short introduction on mixins.

The Iterator-interface is straight forward. You only have to implement the function moveNext and the getter current.

like image 200
Dennis Kaselow Avatar answered Oct 10 '22 04:10

Dennis Kaselow