How does this lambda function work in java 8?

I am trying to use java 8 functions. While reading the 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 the question arose:

Which method will be called in the following expression? "

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

and the answer was

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

As I understand it, since invoke should return a String , it calls Callable invoke. But, I’m not sure how exactly this works.

+5
source share
1 answer

Let's look at the lambda

 invoke(() -> "done"); 

The fact that you only have

 "done" 

makes lambda compatible. A lambda body that does not look executable implicitly becomes

 { return "done";} 

Now, since Runnable#run() has no return value, and Callable#call() is the last one to be selected.

Say what you wrote

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

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

+11
source

Source: https://habr.com/ru/post/1201939/


All Articles