flatMap<U, E extends Exception> method

Result<U, F> flatMap<U, E extends Exception>(
  1. Result<U, F> transform(
    1. S
    )
)

Maps a Result<S, F> to Result<U, F> by applying a function to a contained Success value and unwrapping the produced result, leaving an Failure value untouched.

Use this method to avoid a nested result when your transformation produces another Result type.

In this example, note the difference in the result of using map and flatMap with a transformation that returns an result type.

Example usage:

Result<int, Error> getNextInteger() => Success(random.nextInt(4));
Result<int, Error> getNextAfterInteger(int n) => Success(random.nextInt(n + 1));

final nextIntegerNestedResults = getNextInteger().map(getNextAfterInteger);
print(nextIntegerNestedResults.runtimeType);
`Prints: Success<Result<int, Error>, dynamic>`

final nextIntegerUnboxedResults = getNextInteger().flatMap(getNextAfterInteger);
print(nextIntegerUnboxedResults.runtimeType);
`Prints: Success<int, Error>`

Implementation

Result<U, F> flatMap<U, E extends Exception>(
  Result<U, F> Function(S) transform,
) {
  if (isSuccess) {
    return transform(_left.value);
  } else {
    return Failure(_right.value);
  }
}