ifPresentOrElse method

void ifPresentOrElse([
  1. void action(
    1. T
    )?,
  2. void emptyAction()?
])

If a value is present, performs the given action with the value, otherwise performs the given empty-based action.

action the action to be performed, if a value is present emptyAction the empty-based action to be performed, if no value is present

Throws InvalidArgumentException if a value is present and the given action is null, or no value is present and the given empty-based action is null.

Example

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

name.ifPresentOrElse(
  (value) => print("Found: $value"), // This executes: Found: Frank
  () => print("No value found")
);

empty.ifPresentOrElse(
  (value) => print("Found: $value"),
  () => print("No value found") // This executes: No value found
);

// Useful for handling both cases
void processOptionalData(Optional<String> data) {
  data.ifPresentOrElse(
    (value) => processData(value),
    () => handleMissingData()
  );
}

Implementation

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