javalambdaoption-type

Can I actually return from lambda to return from method and break its execution?


For example:

private String test(Optional myOptional)
{
    myOptional.ifPresent(() -> return "1");
    return "0";
}

so when I call test(myOptional) it will return "1";


Solution

  • 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 Optionals should not be used as a method argument:

    Why should Java 8's Optional not be used in arguments