mapIfNotNull<I, R> method

R? mapIfNotNull<I, R>(
  1. R mapper(
    1. I input
    ), {
  2. R? defaultValue,
})

Maps this value using mapper if it's not null, otherwise returns defaultValue.

Type parameters:

  • I: The expected input type to cast this value to
  • R: The return type of the mapper function

Parameters:

  • mapper: Function to transform the value if it's not null
  • defaultValue: Optional value to return if this is null

Example:

dynamic value = 42;
String result = value.mapIfNotNull<int, String>((n) => 'Number: $n'); // returns: 'Number: 42'

dynamic nullValue;
String result2 = nullValue.mapIfNotNull<int, String>((n) => 'Number: $n', defaultValue: 'N/A'); // returns: 'N/A'

Implementation

R? mapIfNotNull<I, R>(R Function(I input) mapper, {R? defaultValue}) {
  return this == null ? defaultValue : mapper(this);
}