For example:
private String test(Optional myOptional)
{
myOptional.ifPresent(() -> return "1");
return "0";
}
so when I call test(myOptional) it will return "1";
You can't "break" out of the lambda body and return a value from the enclosing method. The return
used in the lambda works only in the scope of the lambda body.
The idiomatic way would be to levarage Optional
API properly:
private String test(Optional<Object> myOptional) {
return myOptional
.map(s -> "1")
.orElse("0");
}
Also, keep in mind that Optional
s should not be used as a method argument: