Java Callable<Void> 作为带有 lambda 的函数式接口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24381302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:52:26  来源:igfitidea点击:

Callable<Void> as Functional Interface with lambdas

javalambdajava-8voidcallable

提问by ferrerverck

I am just learning about new java8 features. And here is my question:

我只是在学习新的 java8 特性。这是我的问题:

Why is it not allowed to use Callable<Void>as a functional interface for lambda expressions? (Compiler complains about returning value) And it is still perfectly legal to use Callable<Integer>there. Here is the sample code:

为什么不允许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();
    }
}

How to explain this behavior?

如何解释这种行为?

采纳答案by Thilo

For a Voidmethod (different from a voidmethod), you have to return null.

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

Voidis just a placeholder stating that you don't actually have a return value (even though the construct -- like Callable here -- needs one). The compiler does not treat it in any special way, so you still have to put in a "normal" return statement yourself.

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