catchOption<T> function

Option<T> catchOption<T>(
  1. Option<T> fn()
)

Executes the given function, returning the returned Option value.

If an OptionError is thrown during the execution of the given function, which occurs when a None value is unwrapped, None will be returned.

This effectively allows safely unwrapping Option values within the given function, propagating None to the returned value in the same way that the ? operator does in Rust. The simplest way to do this is to wrap your function body inside this function like so:

// The equivalent (non-idiomatic) Rust return in divideByTwo() would be:
// return Some(value? / 2);

Option<int> divideByTwo(Option<int> value) => catchOption(() {
  return Some(value.unwrap() ~/ 2);
});

Option<int> foo = Some(42);
Option<int> bar = None();

Option<int> result1 = divideByTwo(foo); // Some(21)
Option<int> result2 = divideByTwo(bar); // None()

Note that any other type of thrown error/exception other than OptionError will be rethrown.

See also: Option.call()

Implementation

Option<T> catchOption<T>(Option<T> Function() fn) {
	try { return fn(); }
	catch (error) { return _handleOptionError(error); }
}