whenNonNull method

T? whenNonNull(
  1. void fn(
    1. T
    )
)

Runs fn with the value when it is non-null, then returns the original receiver unchanged (null or not) so calls can be chained.

A null-safe "tap"/"also": use it for side effects (logging, mutation) without breaking a call chain. fn is never called for a null receiver.

Example:

user?.toListOrEmpty().whenNonNull(print); // prints only when non-null

Implementation

T? whenNonNull(void Function(T) fn) {
  // Pattern matches only when `this` is non-null; `T` is the non-nullable
  // underlying type, so `fn` never receives null.
  if (this case T t) fn(t);
  return this;
}