fold<R> method

R Function(R (T)) fold<R>(
  1. R ifEmpty()
)

returns value returned from ifEmpty thunk if value is null. otherwise, returns value gained from applying function f to this value.

example


int? a = 1;
int? b = null;

a.fold(()=>'none')((elm)=> 'got $elm' ); // => got elm
b.fold(()=>'none')((elm) => 'got $elm' ); => none

Implementation

R Function(R Function(T)) fold<R>(R Function() ifEmpty) {
  if (this == null) {
    return (_) => ifEmpty();
  } else {
    return (f) => f(this!);
  }
}