Lambda works to return a value when SAM method doesnt return a value in java

那年仲夏 提交于 2021-02-19 07:39:27

问题


@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. 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.

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?


回答1:


This is because 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() is simply instructed to invoke the ThreadStatus() method and ignore the return value.



来源:https://stackoverflow.com/questions/51914337/lambda-works-to-return-a-value-when-sam-method-doesnt-return-a-value-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!