Card 01/ 08
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:
Customer findByReference(String ref);
Customer c = findByReference(ref);
System.out.println(c.name());Returning Optional<Customer> moves that fact into the signature:
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.
| Signature says | Caller learns |
|---|---|
Customer | Nothing 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