Reputation: 91
If I'm calling a function from orElse
, the function is executed even if the Optional
is not empty. Is there any way to restrict the execution of the function to only when the Optional
is empty?
Optional.ofNullable(someValue).orElse(someFunction());
Upvotes: 6
Views: 503
Reputation: 393771
someFunction()
gets executed since it's an argument passed to a method, and the arguments passed to a method are evaluated before the method is executed. To avoid the execution, you should pass someFunction()
within a Supplier
instance.
Use orElseGet
instead of orElse
:
Optional.ofNullable(someValue).orElseGet(SomeClass::someFunction);
or
Optional.ofNullable(someValue).orElseGet(()->someFunction());
Upvotes: 13