For example:
private String test(Optional myOptional)
{
myOptional.ifPresent(() -> return "1");
return "0";
}
so when I call test(myOptional) it will return "1";
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.
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.
The lambda functions do not need a return statement, they always return a single expression.
The lambda function assigned to full_name takes two arguments and returns a string interpolating the two parameters first and last .
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:
Why should Java 8's Optional not be used in arguments
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With