I have just begun to use Java 8 and I am wondering if there is a way to write a method that returns a Function
?
Right now I have method like below:
Function<Integer, String> getMyFunction() { return new Function<Integer, String>() { @Override public String apply(Integer integer) { return "Hello, world!" } } }
Is there a way to write that more succinctly in Java 8? I was hoping this would work but it does not:
Function<Integer, String> getMyFunction() { return (it) -> { return "Hello, world: " + it } }
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 body of a lambda expression can contain zero, one or more statements. When there is a single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.
Lambda functions are syntactically restricted to return a single expression. You can use them as an anonymous function inside other functions. The lambda functions do not need a return statement, they always return a single expression.
What is the return type of lambda expression? Explanation: Lambda expression enables us to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button.
Get rid of your return statement inside of your function definition:
Function<Integer, String> getMyFunction() { return (it) -> "Hello, world: " + it; }
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