mapOrNull<TResult extends Object?> method

  1. @optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>({
  1. TResult? left(
    1. Left<L, R> value
    )?,
  2. TResult? right(
    1. Right<L, R> value
    )?,
})

A variant of map that fallback to returning null.

It is equivalent to doing:

switch (sealedClass) {
  case final Subclass value:
    return ...;
  case _:
    return null;
}

Implementation

@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>({
  TResult? Function(Left<L, R> value)? left,
  TResult? Function(Right<L, R> value)? right,
}) {
  final _that = this;
  switch (_that) {
    case Left() when left != null:
      return left(_that);
    case Right() when right != null:
      return right(_that);
    case _:
      return null;
  }
}