Generators

Π΄Π²Π° Ρ‚ΠΈΠΏΠ° Π³Π΅Π½Π΅Ρ€Π°Ρ‚ΠΎΡ€ΠΎΠ²:

  • Synchronous generator: Returns an Iterable object.

  • Asynchronous generator: Returns a Stream object.

// Sync
Iterable<int> naturalsTo(int n) sync* {
  int k = 0;
  while (k < n) yield k++;
}

// Async
Stream<int> asynchronousNaturalsTo(int n) async* {
  int k = 0;
  while (k < n) yield k++;
}

Если Π³Π΅Π½Π΅Ρ€Π°Ρ‚ΠΎΡ€ рСкурсивный, ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅ΠΌ yield*.

Iterable<int> naturalsDownFrom(int n) sync* {
  if (n > 0) {
    yield n;
    yield* naturalsDownFrom(n - 1);
  }
}

Last updated