问题
@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