我刚学习新的
java8功能.这是我的问题:
为什么不允许使用Callable< Void>作为lambda表达式的功能接口? (编译器抱怨返回值)
并且使用Callable< Integer>仍然是完全合法的.那里.以下是示例代码:
public class Test { public static void main(String[] args) throws Exception { // works fine testInt(() -> { System.out.println("From testInt method"); return 1; }); testVoid(() -> { System.out.println("From testVoid method"); // error! can't return void? }); } public static void testInt(Callable<Integer> callable) throws Exception { callable.call(); } public static void testVoid(Callable<Void> callable) throws Exception { callable.call(); } }
如何解释这种行为?
解决方法
对于Void方法(与void方法不同),您必须返回null.
Void只是一个占位符,表明你实际上没有返回值(即使构造 – 像Callable这里 – 需要一个).编译器不会以任何特殊方式处理它,因此您仍然必须自己输入“正常”的返回语句.