Amit yadav
Amit yadav

Reputation: 91

How to prevent the function passed to Optional's orElse from being executed when the Optional is not empty?

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

Answers (1)

Eran
Eran

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

Related Questions