Dart by Example: Generators

  1. main() {
  2. evenNumbersDownFrom(7).forEach(print);
  3. }
  4. // sync* functions return an iterable
  5. Iterable<int> evenNumbersDownFrom(int n) sync* {
  6. // the body isn't executed until an iterator invokes moveNext()
  7. int k = n;
  8. while (k >= 0) {
  9. if (k % 2 == 0) {
  10. // 'yield' suspends the function
  11. yield k;
  12. }
  13. k--;
  14. }
  15. // when the end of the function is executed,
  16. // there are no more values in the Iterable, and
  17. // moveNext() returns false to the caller
  18. }
  1. $ dart generators.dart
  2. 6
  3. 4
  4. 2
  5. 0

by @jryanio | source | license