java - How to prevent the function passed to Optional's orElse from being executed when the Optional is not empty? -
if i'm calling function orelse
, function executed if optional
not empty. there way restrict execution of function when optional
empty?
optional.ofnullable(somevalue).orelse(somefunction());
somefunction()
gets executed since it's argument passed method, , arguments passed method evaluated before method executed. avoid execution, should pass somefunction()
within supplier
instance.
use orelseget
instead of orelse
:
optional.ofnullable(somevalue).orelseget(someclass::somefunction);
or
optional.ofnullable(somevalue).orelseget(()->somefunction());
Comments
Post a Comment