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());
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With