Create a function that accepts an Iterable and generates an Iterable as output. However, the function must not use any methods declared within Iterable and should not create any new variables. (using Dart)


Iterable<T> removeNulls<T>(Iterable<T?> input) sync* {

  for (var item in input) {

    if (item != null) {

      yield item;

    }

  }

}


This implementation uses a generator function (declared with sync*) and the yield keyword to create a new Iterable with only the non-null values. This avoids instantiating a new List explicitly, but it still uses a variable (item) and an iterable method (yield) to create the new Iterable.


More about generators in dart https://dart.dev/guides/language/language-tour#generator 


Generators in Dart are functions that use the yield keyword to return a sequence of values lazily, as they are requested. Instead of computing and returning a complete list of values upfront, generators produce values on demand, which can be more efficient for large or infinite sequences.

In Dart, generators can be implemented using two types of functions: sync* and async*.

sync* functions produce synchronous generators that produce a sequence of values in a non-blocking way. When a sync* function is called, it immediately returns an iterable object that can be used to access the generated values using a for-in loop or other iterable operations.


Comments