The orElse
method looks like this:
public T orElse(T other) {
return value != null ? value : other;
}
There isn't any complex logic here.
As with any method, it will do the following:
- Get the actual values of all parameters passed to the method (which includes calling any methods in those parameters).
- Pass those parameters to the method.
- Execute the method.
The fact that we don't actually care about the value of the parameter doesn't change this process (this is just the way the language has been designed, for better or worse).
If you're looking to not call the method in the parameter, you're probably looking for Optional.orElseGet
.
This:
public static void main(String[] args){
String o = Optional.ofNullable("world").map(str -> "hello" + str)
.orElseGet(() -> dontCallMe());
System.out.println(o);
}
private static String dontCallMe() {
System.out.println("should not have called");
return "why oh why";
}
Outputs only:
helloworld
The difference here is that the thing (Supplier) we're passing to the method will stay () -> dontCallMe()
, it does not become () -> "why oh why"
- only when you call get
does it actually evaluate what's going on there and does dontCallMe
actually get called.