KITFORMA · EDITORIAL ANSWER
Why does Optional.orElse call my expensive fallback even when a value exists?
KitForma editorial guide. A method argument is evaluated before the method can choose whether to use it. A fallback expression can therefore perform work that its result does not need.
Step-by-step answer
candidate.orElseGet(() -> loadDefault()) when the fallback should run only for an empty Optional. Keep orElse for an already computed inexpensive value. If loadDefault changes external state, make its invocation policy explicit rather than hiding it in a convenient expression.
Verify a present value and an empty Optional with a counter around the fallback. The former should not increment it with orElseGet. This is lazy evaluation of the supplier, not memoization: each separate call on an empty Optional can invoke the supplier again.Sources and verification
Sources checked:
Scope: This editorial guide is based on the cited sources and tool behavior. A forum question or a query observed for our site does not establish market search volume, low competition, guaranteed rankings or inadequate answers elsewhere.
This editorial answer was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.