ConceptDifficulty: Intermediate1 min

Optional: A Return Type That Says There Might Be Nothing

The compiler cannot tell you whether findByReference returns null, until the signature says so.

Optional<T> is a container holding either one value of type T or nothing. A method that returns it says, in its signature, that finding nothing is a normal outcome, and the caller cannot reach the value without deciding what to do when it is absent.

A method called findByReference returns a Customer. Whether it can return null (no object at all) is written in the documentation, if anywhere, and the compiler will not help you either way:

java
Customer findByReference(String ref);

Customer c = findByReference(ref);
System.out.println(c.name());
line 4 is either correct or a NullPointerException, and the signature does not say

Returning Optional<Customer> moves that fact into the signature:

java
Optional<Customer> findByReference(String ref);

String name = findByReference(ref)
        .map(Customer::name)
        .orElse("unknown");

The caller now has to say what the name should be when there is no customer. map transforms the value if one is present, and orElse supplies the answer for the empty case; forgetting the empty case is no longer possible without writing something that visibly ignores it.

What each return type tells the caller
Signature saysCaller learns
CustomerNothing about absence; must read the documentation or guess
Optional<Customer>Absence is expected, and the compiler will not let it be ignored

So Optional is documentation the compiler enforces. It exists for one job: a method saying "there might be nothing to return" in a way a caller cannot miss, and the rest of this topic is about using it for that job and no other.

← → move through sections and cards