Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 435
Amit yadav Avatar asked Nov 08 '16 12:11

Amit yadav


1 Answers

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());
like image 126
Eran Avatar answered Sep 29 '22 02:09

Eran