简体   繁体   中英

How does this lambda feature in java 8 work?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM