当SAM方法未在Java中返回值时,Lambda会返回一个值 [英] Lambda works to return a value when SAM method doesnt return a value in java
问题描述
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
public class MethodReference1 {
public static String ThreadStatus() {
System.out.println( Thread.currentThread().getName() + " is running...");
return "threadname";
}
public static void main(String[] args) {
Thread t1 = new Thread(() -> ThreadStatus());
t1.start();
}
}
在上述使用Java 8的示例中,ThreadStatus()返回一个字符串,但Runnable接口"run()"方法未返回任何值.但它仍然有效(无编译/运行时错误).我想知道它是如何工作的,因为根据lamba规范,SAM应该具有完全相同的签名.
In the above example using Java 8, ThreadStatus() returns a string but Runnable interface "run()" method doesnt return any value. But it still works (No compile/runtime error). I am wondering how it is working because as per the lamba specification, SAM should have exactly same signature.
如果我翻转了ThreadStatus方法不返回任何值的情况,并更改了Functional接口方法以返回值,则会出现编译时错误.
If i flip the case where ThreadStatus method doesnt return any value and change the Functional interface method to return a value, i get a compile time error.
有人可以帮助我理解这一点吗?
Can someone help me understand this?
推荐答案
这是因为Thread t1 = new Thread(() -> ThreadStatus());
等效于:
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
ThreadStatus();
}
});
因此您不会从run()
返回任何内容.只需指示run()
调用ThreadStatus()
方法并忽略返回值即可.
So you're not returning anything from run()
. run()
is simply instructed to invoke the ThreadStatus()
method and ignore the return value.
这篇关于当SAM方法未在Java中返回值时,Lambda会返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!