How do you use Optional properly? How does orElse differ from orElseGet?
Short answer
Optional is a return type for methods that may "have no result", forcing callers to handle the empty case. orElse(x) always evaluates x, orElseGet only when empty.
3 points to say:
- Use it only as a return type, not as a field or parameter.
- For an expensive default (a DB query), use
orElseGet. - Services usually use
orElseThrow.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.