可调用<Void>作为lambdas的功能接口

fer*_*rck 11 java lambda callable void java-8

我刚学习新的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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如何解释这种行为?

Thi*_*ilo 23

对于Void方法(与方法不同void),您必须返回null.

Void只是一个占位符,表明你实际上没有返回值(即使构造 - 像Callable这里 - 需要一个).编译器不会以任何特殊方式处理它,因此您仍然必须自己输入"正常"的返回语句.

  • 编译器不会将`Void`视为`void`.它像任何其他类一样对待它,所以你需要返回一些`Void`的实例(其中没有),或者失败,`null`. (5认同)