无法将void转换为java.lang.Void [英] Cannot convert void to java.lang.Void
问题描述
我正在尝试执行以下操作
I'm trying to do the following
interface Updater {
void update(String value);
}
void update(Collection<String> values, Updater updater) {
update(values, updater::update, 0);
}
void update(Collection<String> values, Function<String, Void> fn, int ignored) {
// some code
}
但我收到此编译错误:
"Cannot convert void to java.lang.Void"
这意味着 updater :: update
不能用作函数< String,Void>
。
当然我不能写功能< String,void>
而且我不想改变返回类型更新()
到无效
。
Of course I can't write Function <String, void>
and I don't want to change return type of update()
to Void
.
如何解决此问题?
推荐答案
A 函数
返回一个值,即使它被声明为类型 Void
(你必须返回 null
然后。相比之下, void
方法确实没有返回任何内容,甚至 null
。所以你必须插入 return
声明:
A Function
returns a value, even if it is declared as being of type Void
(you will have to return null
then. In contrast, a void
method really returns nothing, not even null
. So you have to insert the return
statement:
void update(Collection<String> values, Updater updater) {
update(values, s -> { updater.update(); return null; }, 0);
}
另一种方法是将函数< String,Void>
更改为 Consumer< String>
,然后你可以使用方法参考:
An alternative would be to change the Function<String,Void>
to Consumer<String>
, then you can use the method reference:
void update(Collection<String> values, Updater updater) {
update(values, updater::update, 0);
}
void update(Collection<String> values, Consumer<String> fn, int ignored) {
// some code
}
这篇关于无法将void转换为java.lang.Void的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!