[英]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();
}
}
In the above example using Java 8, ThreadStatus() returns a string but Runnable interface "run()" method doesnt return any value. 在上面使用Java 8的示例中,ThreadStatus()返回一个字符串,但是Runnable接口“ run()”方法不返回任何值。 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. 我想知道它是如何工作的,因为根据lamba规范,SAM应该具有完全相同的签名。
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. 如果我翻转了ThreadStatus方法不返回任何值的情况,并将Functional接口方法更改为返回值,我将收到编译时错误。
Can someone help me understand this? 有人可以帮我理解吗?
This is because Thread t1 = new Thread(() -> ThreadStatus());
这是因为Thread t1 = new Thread(() -> ThreadStatus());
is equivalent to: 等效于:
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
ThreadStatus();
}
});
So you're not returning anything from run()
. 因此,您不会从run()
返回任何内容。 run()
is simply instructed to invoke the ThreadStatus()
method and ignore the return value. 只需指示run()
调用ThreadStatus()
方法并忽略返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.