or method

Optional<T> or([
  1. Optional<T> supplier()?
])

If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function.

supplier the supplying function that produces an Optional to be returned

Returns an Optional describing the value of this Optional, if a value is present, otherwise an Optional produced by the supplying function.

Throws InvalidArgumentException if the supplying function is null or produces null.

Example

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

// If primary has value, use it; otherwise use backup
Optional<String> result1 = primary.or(() => Optional.of("backup"));
print(result1.get()); // "primary"

Optional<String> result2 = empty.or(() => Optional.of("backup"));
print(result2.get()); // "backup"

// Chain multiple fallbacks
Optional<String> config = Optional.empty<String>()
    .or(() => getFromEnvironment())
    .or(() => getFromConfigFile())
    .or(() => Optional.of("default"));

// Lazy evaluation - supplier only called when needed
Optional<String> expensive = empty.or(() {
  print("Computing expensive default...");
  return Optional.of("expensive result");
}); // "Computing expensive default..." is printed

Implementation

Optional<T> or([Optional<T> Function()? supplier]) {
  if (supplier == null) {
    throw InvalidArgumentException('supplier cannot be null');
  }
  if (isPresent()) {
    return this;
  } else {
    Optional<T> result = supplier();
    if (result.isEmpty()) {
      throw InvalidArgumentException('supplier returned null');
    }

    return result;
  }
}