11

我正在尝试将下面的 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);
}

...
4

2 回答 2

12

通过使用IterableMixin你只需要实现iterator-function。

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

访问http://blog.sethladd.com/2013/03/first-look-at-dart-mixins.html以了解有关 mixins 的简短介绍。

-Iterator界面是直截了当的。您只需要实现函数moveNext和 getter current

于 2013-04-20T06:03:20.427 回答
2

Soo 我尝试了这个,这不是我想要的,因为我不想扩展基类。

/**
 * 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;
}  
于 2013-04-20T06:11:20.463 回答