Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";

like image 531
user2620644 Avatar asked Aug 03 '17 12:08

user2620644


People also ask

Can you return from a lambda Java?

A return statement is not an expression in a lambda expression. We must enclose statements in braces ({}). However, we do not have to enclose a void method invocation in braces. The return type of a method in which lambda expression used in a return statement must be a functional interface.

Can we replace lambda expression with method reference?

The method references can only be used to replace a single method of the lambda expression. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same.

Can we use return in lambda?

The lambda functions do not need a return statement, they always return a single expression.

Can lambda return string?

The lambda function assigned to full_name takes two arguments and returns a string interpolating the two parameters first and last .


2 Answers

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

like image 158
Grzegorz Piwowarek Avatar answered Sep 30 '22 01:09

Grzegorz Piwowarek


The issue you're having is that the return is taken as the return of the lambda function, not the return of the 'test' function.

Optional.ifPresent is not expecting to be given a function that returns a value. It expects a Consumer<T> which is effectively a function which takes exactly one parameter and returns nothing. As a normal function, rather than a lambda it would look something like this:

void myConsumer(String s)
{
    System.out.println(s);
}

You probably want to use isPresent ('is' not 'if'):

if (myOptional.isPresent())
{
     return "1";
}
else
{
     return "0";
}

or using a ternary operator:

return myOptional.isPresent() ? "1" : "0";

As an aside, you are using the raw type of Optional. This will result in a compiler warning. You should declare what type the Optional will hold by using generics:

Optional<String> myOptional = /*something*/;

This will give you compile-time type safety that the Optional won't hold values other than strings.

like image 40
Michael Avatar answered Sep 30 '22 03:09

Michael