简体   繁体   English

java 8中的lambda特性如何工作?

[英]How does this lambda feature in java 8 work?

I am trying to use java 8 features. 我正在尝试使用java 8功能。 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; invoke(Callable<T>)方法invoke(Callable<T>)因为该方法返回一个值; the method invoke(Runnable) does not. 方法invoke(Runnable)没有。 In this case, the type of the lambda expression () -> "done" is Callable<T> . 在这种情况下,lambda表达式() -> "done"Callable<T>

As I understand since invoke is expected to return a String , it calls Callable's invoke. 据我所知,因为invoke应该返回一个String ,它会调用Callable的调用。 But, not sure how exactly it works. 但是,不确定它是如何工作的。

Let's take a look at the lambda 我们来看看lambda

invoke(() -> "done");

The fact that you only have 事实上你只有

"done"

makes the lambda value compatible . 使lambda 值兼容 The body of the lambda, which doesn't appear to be an executable statement, implicitly becomes lambda的主体,似乎不是一个可执行语句,隐含地变成了

{ return "done";} 

Now, since Runnable#run() doesn't have a return value and Callable#call() does, the latter will be chosen. 现在,由于Runnable#run()没有返回值而Callable#call()没有,后者将被选中。

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. 相反,lambda将被解析为Runnable类型的实例,因为没有可以用作返回值的表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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