orElse method

T? orElse(
  1. T? other
)

If a value is present, returns the value, otherwise returns other.

other the value to be returned, if no value is present. May be null.

Returns the value, if present, otherwise other.

Example

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

print(name.orElse("Unknown")); // "Jack"
print(empty.orElse("Unknown")); // "Unknown"

// Can provide null as default
String? result = empty.orElse(null);
print(result); // null

// Useful for providing defaults
String getUserName(Optional<String> optionalName) {
  return optionalName.orElse("Guest");
}

// With complex objects
class Config {
  final String host;
  final int port;
  Config(this.host, this.port);
}

Optional<Config> userConfig = Optional.empty();
Config defaultConfig = Config("localhost", 8080);
Config config = userConfig.orElse(defaultConfig);

Implementation

T? orElse(T? other) {
  return _value != null ? _value as T : other;
}