Maybe<T extends Object> extension

A Maybe monad that may or may not contain a T.

All nullable types are Maybe monads. Leveraging on the type system, this implementation is not an explicit container.

Assuming:

Maybe(T) = Some(T) | None()

It can be represented in the type system as:

T? = T | null

Example:

String foo(int? bar) { // int? is a Maybe(int) monad.
  return bar.where((e) => e == 1).map((e) => e.toString())!;
}

Maybe and collections

It is recommended to use an empty collection to represent None(). Thus, most of Maybe's functions deliberately do not work on collections.

Good:

List<String> foo() {
  if (notFound) return [];
}

Bad:

List<String>? foo() {
  if (notFound) return null;
}

See:

  • FutureMaybe for working with asynchronous Maybes.
  • Result for representing successes and failures.
on
  • T?

Methods

bind<R>(R? function(T value)) → R?

Available on T?, provided by the Maybe extension

Returns R? produced by function if this is not null. Otherwise returns null.
map<R extends Object>(R function(T value)) → R?

Available on T?, provided by the Maybe extension

Returns R if this is not null. Otherwise returns null.
where(Predicate<T> predicate) → T?

Available on T?, provided by the Maybe extension

Returns this if it is not null and satisfies predicate. Otherwise returns null.