Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nonlocal return from lambda?

I am very new to programming so be gentle please! :D

public void test(Optional<String> testString){
    testString.ifPresent(s -> {
        //do stuff...
        System.out.println("Exit method");
        return;
    });
    //Log if it was not present
    Logger.log("...");
}

Here you have a code snippet. If the optional is present I do some stuff and want to exit the method by just calling return. I now wonder why my logger logs something although the testString is present. Can someone maybe point out what I'm missing please ? Thank you !

like image 586
IonicBlaze Avatar asked Jan 22 '26 20:01

IonicBlaze


1 Answers

The problem is that when you do:

 testString.ifPresent(s -> {
        //do stuff...
        System.out.println("Exit method");
        return;
    });

You return from a lambda function, and not from the test(), as you expect.

Try using isPresent:

    if (testString.isPresent()) {
        System.out.println("Exit method");
        return;
    }
    //Log if it was not present
    System.out.println("Not present");
like image 187
Alexey Soshin Avatar answered Jan 25 '26 23:01

Alexey Soshin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!