mapOrElse<U> method
Maps a Result<T, E> to a Result<U, E> using the given mapFn function with
the held value if the Result is Ok. Otherwise returns the result of
orFn as Ok(orFn()).
orFn will only be evaluated if this Result is Err.
Result<int, String> a = Ok(1);
Result<int, String> b = Err('foo');
print(a.mapOrElse(() => 5, (val) => val + 1).unwrap()); // prints: 2
print(b.mapOrElse(() => 5, (val) => val + 1).unwrap()); // prints: 5
Note: Unlike Rust's
Result.map_or_else(),
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_else()
Implementation
Result<U, E> mapOrElse<U>(U Function() orFn, U Function(T) mapFn) {
return switch (this) {
Ok(:T v) => Ok(mapFn(v)),
Err() => Ok(orFn()),
};
}