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

3

6

For example:

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

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

Alimentary answered 3/8, 2017 at 12:45 Comment(7)
You can return a Function. Does that fit your need? You would call test().apply()Blowtube
Well, you wrote the code, does it work? Just put it in a class and run it.Jezabelle
Possible duplicate of Return Lambda from Method in Java 8?Sexivalent
The exemple returns another lambda, but it's the same way of doing if you just want to return a stringSexivalent
Not in Java. I think Kotlin supports that. BTW your code is equivalent to myOptional.map(item -> "1").orElse("0"). Maybe you should consider another exampleBrnaba
@Sexivalent no, he is asking about a possibility of terminating the enclosing method and returning the value from the inside of a lambdaAntenatal
If you found your answer, please accept itAntenatal
A
9

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

Antenatal answered 3/8, 2017 at 12:53 Comment(3)
Good answer. Better than mine. I'd change the function to definition to: private <T> String test(Optional<T> myOptional)Marya
@Marya hard to say what was the OP's intention here but surely it's one of the valid optionsAntenatal
Perfect answer, thank you! But it's not possible to break the method's execution just to avoit next method instructions to execute, right?Alimentary
M
1

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.

Marya answered 3/8, 2017 at 12:52 Comment(2)
I think he is asking about a return that breaks from the whole methodAntenatal
@pivovarit Yep. Your answer made me realise. I'll edit my answer slightly.Marya
B
0

Use Atomic classes, which allows define value

public void executeAction(final Consumer<EntityManager> action) {
    //Any code
}


final AtomicInteger rowsDeleted = new AtomicInteger();

jpaManager.executeAction((aux) -> {
        rowsDeleted.set(aux.createQuery(delete).executeUpdate());
});

return rowsDeleted.get();
Boroughenglish answered 24/8 at 14:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.