SteelReed

Search

Search posts, questions…

Java CoreQuestion 33 / 43

Middle

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.

yesempty, cheap defaultempty, costly defaultempty is an errorrepo.findById(id)Optional has a value?map, take the valueorElse(constant)orElseGet(supplier)orElseThrow

3 points to say:

  1. Use it only as a return type, not as a field or parameter.
  2. For an expensive default (a DB query), use orElseGet.
  3. 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.