Skip to content
Optional<T>
step 1/4

Reading — step 1 of 4

Learn

~1 min readErrors and Optionals

Optional<T> is Java's wrapper for "value or absent" — alternative to returning null. Forces callers to handle the empty case.

Creation:

Optional<String> some = Optional.of("hello");          // throws if null
Optional<String> empty = Optional.empty();
Optional<String> nullable = Optional.ofNullable(maybeNull);

Consumption:

Optional<User> u = findById(id);

// most common patterns:
String name = u.map(User::getName).orElse("unknown");
u.ifPresent(user -> log(user));
User user = u.orElseThrow(() -> new NotFoundException(id));

// chaining:
int nameLength = findById(id)
    .map(User::getName)
    .map(String::length)
    .orElse(0);

Anti-patterns to avoid:

  • if (opt.isPresent()) opt.get() — use ifPresent or orElse
  • Optional as a field type — use null (or annotations); Optional is for return values
  • Optional as a method parameter — overload with/without instead

Optional is well-suited for return types of methods that may not have a value (DB lookups, parses).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…