mapOr<U> method

Result<U, E> mapOr<U>(
  1. U orValue,
  2. U mapFn(
    1. T
    )
)

Maps a Result<T, E> to a Result<U, E> using the given function with the held value if the Result<T, E> is Ok. Otherwise returns the provided orValue as Ok(orValue).

Values passed for orValue are eagerly evaluated. Consider using Result.mapOrElse() to provide a default that will not be evaluated unless the Result is Ok.

Result<int, String> a = Ok(1);
Result<int, String> b = Err('foo');

print(a.mapOr(5, (val) => val + 1).unwrap()); // prints: 2
print(b.mapOr(5, (val) => val + 1).unwrap()); // prints: 5

Note: Unlike Rust's Result.map_or(), this method returns a Result value. Given that Result.map() returns the mapped Result it just made sense for this method to do the same.

See also: Rust: Result::map_or()

Implementation

Result<U, E> mapOr<U>(U orValue, U Function(T) mapFn) => switch (this) {
	Ok(value: T value) => Ok(mapFn(value)),
	Err() => Ok(orValue)
};