我正在尝试将下面的Java代码移植到Dart,我很困惑这样做。
在Java中,Iterable接口是使用一种方法清理的地方,实现这一点非常简单。
这段代码如何最好地转换为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);
}
...
答案 0 :(得分:9)
使用IterableMixin
,您只需要实现iterator
- 函数。
class ChessSquares extends Object with IterableMixin<ChessSquare> {
Iterator<ChessSquare> iterator() => new ChessSquaresIterator(bits);
...
}
访问http://blog.sethladd.com/2013/03/first-look-at-dart-mixins.html,了解关于mixins的简短介绍。
Iterator
- 界面很简单。您只需要实现函数moveNext
和getter current
。
答案 1 :(得分:1)
所以我尝试了这个,这不是我想要的,因为我不想扩展基类。
/**
* 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;
}