collect<T, E> static method

  1. @useResult
Result<T, E> collect<T, E>(
  1. Result<T, E> collector(
    1. U check<U>(
      1. Result<U, E> result
      )
    )
)

Encloses any number of operations, optionally returning early on Err.

See collectAsync for an asynchronous version of this function.

Examples

final collected = Result.collect<int, String>((check) {
  // This passes the check and `first` gets the value `2`
  final first = check(const Ok(2));

  // This fails the check and the error is returned from the collector
  final second = check(const Err<int, String>('error'));

  // This is never reached
  return Ok(first + second);
});

// prints "Err(error)"
print(collected);

Implementation

@useResult
static Result<T, E> collect<T, E>(
  Result<T, E> Function(U Function<U>(Result<U, E> result) check) collector,
) {
  try {
    return collector(<U>(result) {
      return switch (result) {
        Ok(:final value) => value,
        Err(:final error) => throw _CheckException<T, E>(Err(error))
      };
    });
  } on _CheckException<T, E> catch (ex) {
    return ex.err;
  }
}