ifPresent method

void ifPresent([
  1. void action(
    1. T
    )?
])

If a value is present, performs the given action with the value, otherwise does nothing.

action the action to be performed, if a value is present

Throws InvalidArgumentException if value is present and the given action is null.

Example

Optional<String> name = Optional.of("Eve");
Optional<String> empty = Optional.empty();

name.ifPresent((value) => print("Hello, $value!")); // Hello, Eve!
empty.ifPresent((value) => print("This won't print"));

// Useful for side effects
Optional<List<String>> items = Optional.of(["a", "b", "c"]);
items.ifPresent((list) => list.add("d"));

Implementation

void ifPresent([void Function(T)? action]) {
  if (action == null) {
    throw InvalidArgumentException('action cannot be null');
  }
  if (_value != null) {
    action(_value as T);
  }
}