mapOr<U> method
Maps this Option<T>
to an Option<U>
using the given function with the
held value if this Option<T>
is Some. Otherwise returns the provided
orValue
as Some(orValue)
.
Values passed for orValue
are eagerly evaluated. Consider using Option.mapOrElse()
to provide a default that will not be evaluated unless this Option
is None.
Option<int> a = Some(1);
Option<int> b = None();
print(a.mapOr(5, (val) => val + 1).unwrap()); // prints: 2
print(b.mapOr(5, (val) => val + 1).unwrap()); // prints: 5
Note: Unlike Rust's
Option::map_or(),
this method returns an Option
value. Given that Option.map() returns
the mapped Option
it just made sense for this method to do the same.
See also:
Rust: Option::map_or()
Implementation
Option<U> mapOr<U>(U orValue, U Function(T) mapFn) => switch (this) {
Some(value: T value) => Some(mapFn(value)),
None() => Some(orValue)
};