【发布时间】:2015-12-16 15:53:48
【问题描述】:
我这辈子都找不到以下解释:
public static void takesAFunction(Function<String, Void> func) {
func.apply("Hi I'm running a function");
}
public static void takesAConsumer(Consumer<String> func) {
func.accept("Hi I'm running a consumer");
}
public static void main(String[] args) throws Exception {
takesAFunction((String str) -> { System.out.println(str); });
takesAConsumer((String str) -> { System.out.println(str); });
}
我正在使用 JDK 1.8.0_66 和线路
takesAFunction((String str) -> { System.out.println(str); });
被标记为错误提示
The method takesAFunction(Function<String,Void>) in the type MyClass
is not applicable for the arguments ((String str) -> {})
我不明白是怎么回事
Function<String, Void>
不同于
Consumer<String>
当两者都没有返回并且都接受一个字符串参数时。
有人可以解释一下这个因为它正在杀人吗。
提前致谢!
【问题讨论】:
-
您没有返回
Void值。 -
同样,
Runnable和Callable<Void>之间也有区别,因为Void是对只能是null的类的引用(除非您使用反射来创建一个)跨度>
标签: java lambda java-8 runnable callable