Option<T> constructor

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

Creates a context for early return, similar to "Do notation". Works like the Rust "?" operator, which is a "Early Return Operator". Here "$" is used as the "Early Return Key". when "$" is used on a type _None, immediately the context that "$" belongs to is returned with None(). e.g.

  Option<int> intNone() => const None();

  Option<int> earlyReturn(int val) => Option(($){
    int x = intNone()[$]; // returns [None] immediately
    return Some(val + 3);
  });
  expect(earlyReturn(2), const None());

This should be used at the top level of a function as above. Passing "$" to any other functions, nesting, or attempting to bring "$" out of the original scope should be avoided.

Implementation

@pragma("vm:prefer-inline")
factory Option(_OptionEarlyReturnFunction<T> fn) {
  try {
    return fn(const _OptionEarlyReturnKey._());
  } on _OptionEarlyReturnNotification catch (_) {
    return None;
  }
}