Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Lambda from Method in Java 8?

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 }  } 
like image 383
Philip Lombardi Avatar asked Nov 06 '14 04:11

Philip Lombardi


People also ask

How do you return a lambda function in 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.

What is the return type of lambda expression in Java 8?

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.

How do I return from lambda?

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?

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.


1 Answers

Get rid of your return statement inside of your function definition:

Function<Integer, String> getMyFunction() {     return (it) -> "Hello, world: " + it; } 
like image 179
mkobit Avatar answered Sep 23 '22 18:09

mkobit