How to implement Iterable <E>

I am trying to port the Java code below to Dart, and I am puzzled by this.

In Java, the Iterable interface is clean with a single method, and you can implement it.

How is this code best transformed into 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);
}

...
+5
source share
2 answers

Soo I tried this, but that’s not what I need, since I don’t want to extend the base class.

/**
 * Chess squares represented as a bitmap.
 */
class ChessSquares extends IterableBase<ChessSquare> {

  Iterator<ChessSquare> get iterator {
    return new ChessSquaresIterator(this);
  }

  ...

}

class ChessSquaresIterator extends Iterator<ChessSquare> {
  int _nextBit;
  int64 _bits;
  ChessSquare _current;

  ChessSquaresIterator(ChessSquares squares) {
    _bits = new int64.fromInt(squares._bits); 
  }

  bool moveNext() {
    _nextBit = _bits.numberOfTrailingZeros();
    if (_nextBit < 64) {
      _current = ChessSquare.values()[_nextBit];
      _bits = _bits & ~_current.bit();
    } else {
      _current = null;
    }
    return _nextBit < 64;
  }

  E get current => _current;
}  
+1
source

Using IterableMixin, you only need to implement the iterator-function.

class ChessSquares extends Object with IterableMixin<ChessSquare> {
    Iterator<ChessSquare> iterator() => new ChessSquaresIterator(bits);
    ...
}

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

The interface iteratoris straightforward. You need to implement the function moveNextand getter current.

+6
source

All Articles