map<A2, B2> method

Union2<A2, B2> map<A2, B2>(
  1. A2 first(
    1. A value
    ),
  2. B2 second(
    1. B value
    )
)

Transforms a union into another union of potentially different types.

The map function is useful when we want to modify the current value, and the result is still a union.

Example:

Union2<String, int> union;

Union2<String, int> modifiedValue = union.map(
  (value) => 'Hello $value',
  (value) => value * 2,
);

This previous snippet will do two things:

  • if the value is a String, it'll prefix the value by Hello .
  • if it's an int instead, the value will be multiplied by 2.

So original union is not modified, and a new union is created instead.

The result of a callback doesn't have to be of the same type than the value type.

See also:

  • join, similar to map but with more freedom on the result.

Implementation

// ignore: missing_return, the switch always return
Union2<A2, B2> map<A2, B2>(
  A2 first(A value),
  B2 second(B value),
) {
  late Union2<A2, B2> res;
  this(
    (a) {
      final value = first(a);
      res = (f, _b, _c, _d, _e, _f, _g, _h, _i) => f(value);
    },
    (a) {
      final value = second(a);
      res = (_, f, _c, _d, _e, _f, _g, _h, _i) => f(value);
    },
    _noop,
    _noop,
    _noop,
    _noop,
    _noop,
    _noop,
    _noop,
  );
  return res;
}