I've encountered an unexpected behavior while using the Optional API in Java.
Session session = sessionService
.getSessionById(id)
.orElse(
sessionService.createSession(
new Session(...)
)
);
The above code executes the getSessionById() method returns the found object but then it also executes what's inside the orElse() method which shouldn't be possible since the object is present.
Why would the method inside orElse()
get called before evaluating the presence of the Optional object first?
orElse()
takes a value to return instead. In order to hand that value to the method, you need to compute it. That means in order to callorElse
, theSession
object must already exist. To avoid this, pass useorElseGet
with aSupplier<Session>
(trivial conversion:orElseGet( () => sessionService.createSession(...) )
.() -> sessionService.creationSession(...)