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);
}
...
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With