How to implement Iterable<E> in dart? -


i still havn't understood how deal iterable/iterator in dart.

i think have give , return lists that's not want since lead bad performance in case.

what want understand how implement own iterable/iterator.

why both of these attempts fail?

library foo;  import 'dart:collection';  // both attemps below raises following error: // ============================================== // // closure call mismatched arguments: function 'movenext' // // nosuchmethoderror: incorrect number of arguments passed method named 'movenext' // receiver: closure: (dynamic) => iterator<int> function 'iterator':. // tried calling: movenext()   main() {   iterable<int> iterable1 = new oddsiterabledartstyle([1,2,4,6,7,8,9]);   (int in iterable1)     print("odd: $i");    iterable<int> iterable2 = new oddsiterablejavastyle([1,2,4,6,7,8,9]);   (int in iterable2)     print("odd: $i"); }  // ------------------------------------------  class oddsiterabledartstyle extends object iterablemixin<int> {   list<int> _ints;    oddsiterabledartstyle(this._ints);    iterator<int> iterator() {     return new oddsiterator(this);   } }  // ------------------------------------------  class oddsiterablejavastyle implements iterable<int> {   list<int> _ints;    oddsiterablejavastyle(this._ints);    iterator<int> iterator() {     return new oddsiterator(this);   }  }  // ------------------------------------------  class oddsiterator implements iterator<int> {  // iterate on odd numbers   list<int> _ints;   int _index;    oddsiterator(this._ints) {     _index = -1;   }    bool movenext() {     while (++_index < _ints.length) {       if (_ints[_index].isodd)         return true;     }     return false;   }    int current => (_index < 0) ? null : _ints[_index]; } 

i see 2 immediate problems:

  1. iterator getter. code shouldn't read iterator<int> iterator() { ... }, should iterator<int> iterator { ... } instead.

  2. your iterators expecting underlying integer lists, passing in wrapper. want construct iterator new oddsiterator(_ints), not new oddsiterator(this).

btw, iterator supposed return null if call current , have moved beyond end.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

keyboard - C++ GetAsyncKeyState alternative -

android - java.net.UnknownHostException(Unable to resolve host “URL”: No address associated with hostname) -