collect<T> static method
Encloses any number of operations, optionally returning early on None.
See collectAsync for an asynchronous version of this function.
Examples
final collected = Option.collect<int>((check) {
// This passes the check and `first` gets the value `2`
final first = check(const Some(2));
// This fails the check and no value is returned from the collector
final second = check(const None<int>());
// This is never reached
return Some(first + second);
});
// prints "None"
print(collected);
Implementation
@useResult
static Option<T> collect<T>(
Option<T> Function(U Function<U>(Option<U> option) check) collector,
) {
try {
return collector(<U>(option) {
return switch (option) {
Some(:final value) => value,
None() => throw const _CheckException()
};
});
} on _CheckException {
return None<T>();
}
}