get method

T get()

If a value is present, returns the value, otherwise throws InvalidArgumentException.

API Note

The preferred alternative to this method is orElseThrow.

Returns the non-null value described by this Optional.

Throws InvalidArgumentException if no value is present.

Example

Optional<String> name = Optional.of("Bob");
print(name.get()); // "Bob"

Optional<String> empty = Optional.empty();
try {
  print(empty.get());
} catch (e) {
  print("Error: $e"); // Error: Bad state: No value present
}

Implementation

T get() {
  if (_value == null) {
    throw InvalidArgumentException('No value present');
  }
  return _value as T;
}