Iterable<E>.generate constructor

Iterable<E>.generate(
  1. int count, [
  2. E generator(
    1. int index
    )?
])

Creates an Iterable which generates its elements dynamically.

The generated iterable has count elements, and the element at index n is computed by calling generator(n). Values are not cached, so each iteration computes the values again.

If generator is omitted, it defaults to an identity function on integers (int x) => x, so it may only be omitted if the type parameter allows integer values. That is, if E is a super-type of int.

As an Iterable, Iterable.generate(n, generator)) is equivalent to const [0, ..., n - 1].map(generator).

Implementation

factory Iterable.generate(int count, [E generator(int index)?]) {
  // Always OK to omit generator when count is zero.
  if (count <= 0) return EmptyIterable<E>();
  if (generator == null) {
    // If generator is omitted, we generate integers.
    // If `E` does not allow integers, it's an error.
    Function id = _GeneratorIterable._id;
    if (id is! E Function(int)) {
      throw ArgumentError(
          "Generator must be supplied or element type must allow integers",
          "generator");
    }
    generator = id;
  }
  return _GeneratorIterable<E>(count, generator);
}