【问题标题】:Java 8 Function<String, Void> vs Consumer<String> [duplicate]Java 8 Function<String, Void> vs Consumer<String> [重复]
【发布时间】: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 值。
  • 同样,RunnableCallable&lt;Void&gt; 之间也有区别,因为Void 是对只能是null 的类的引用(除非您使用反射来创建一个)跨度>

标签: java lambda java-8 runnable callable


【解决方案1】:

Function&lt;String, Void&gt; 应具有以下签名:

Void m(String s);

不要与void m(String s);混淆!

所以你需要返回一个Void 值——唯一可用的是null

takesAFunction((String str) -> {
  System.out.println(str);
  return null;
});

按预期编译。

【讨论】:

  • 哦,明白了 - 非常感谢!
猜你喜欢
  • 2020-03-17
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 2011-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多