Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this lambda feature in java 8 work?

Tags:

java

java-8

I am trying to use java 8 features. While reading official tutorial I came across this code

static void invoke(Runnable r) {
    r.run();
}

static <T> T invoke(Callable<T> c) throws Exception {
    return c.call();
}

and there was a question:

Which method will be invoked in the following statement?"

String s = invoke(() -> "done");

and answer to it was

The method invoke(Callable<T>) will be invoked because that method returns a value; the method invoke(Runnable) does not. In this case, the type of the lambda expression () -> "done" is Callable<T>.

As I understand since invoke is expected to return a String, it calls Callable's invoke. But, not sure how exactly it works.

like image 998
would_like_to_be_anon Avatar asked Sep 05 '14 18:09

would_like_to_be_anon


People also ask

Why do we add lambda in Java 8?

Introduction. Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection .

How does lambda expression works internally in Java?

Whenever a java compiler translates a lambda expression into byte code, it copies the lambda's body into a private method or private static method inside of the class in which expression is defined.

How do lambda functions work?

Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).

What are the characteristics of a Java 8 lambda expression?

Characteristics of Lambda Expression Optional Type Declaration − There is no need to declare the type of a parameter. The compiler inferences the same from the value of the parameter. Optional Parenthesis around Parameter − There is no need to declare a single parameter in parenthesis.


1 Answers

Let's take a look at the lambda

invoke(() -> "done");

The fact that you only have

"done"

makes the lambda value compatible. The body of the lambda, which doesn't appear to be an executable statement, implicitly becomes

{ return "done";} 

Now, since Runnable#run() doesn't have a return value and Callable#call() does, the latter will be chosen.

Say you had written

invoke(() -> System.out.println());

instead, the lambda would be resolved to an instance of type Runnable, since there is no expression that could be used a return value.

like image 121
Sotirios Delimanolis Avatar answered Oct 12 '22 17:10

Sotirios Delimanolis