无法将 void 转换为 java.lang.Void
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28762715/
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
Cannot convert void to java.lang.Void
提问by Kastaneda
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
}
but I get this compiler error:
但我收到此编译器错误:
"Cannot convert void to java.lang.Void"
That means updater::update
cannot be used as Function<String, Void>
.
这意味着updater::update
不能用作Function<String, Void>
.
Of course I can't write Function <String, void>
and I don't want to change return type of update()
to Void
.
当然,我不能写Function <String, void>
,我不想改变返回类型update()
来Void
。
How do I resolve this problem?
我该如何解决这个问题?
回答by Holger
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:
AFunction
返回一个值,即使它被声明为类型Void
(你将不得不返回null
。相反,一个void
方法实际上什么都不返回,甚至不返回null
。所以你必须插入return
语句:
void update(Collection<String> values, Updater updater) {
update(values, s -> { updater.update(); return null; }, 0);
}
An alternative would be to change the Function<String,Void>
to Consumer<String>
, then you can use the method reference:
另一种方法是将 更改Function<String,Void>
为Consumer<String>
,然后您可以使用方法引用:
void update(Collection<String> values, Updater updater) {
update(values, updater::update, 0);
}
void update(Collection<String> values, Consumer<String> fn, int ignored) {
// some code
}
回答by Hoopje
A function returns a value. What you are looking for is the java.util.function.Consumer
interface. This has an void accept(T)
method and doesn't return a value.
函数返回一个值。您正在寻找的是java.util.function.Consumer
界面。这有一个void accept(T)
方法并且不返回值。
So you method becomes:
所以你的方法变成:
void update(Collection<String> values, Consumer<String> fn, int ignored) {
// some code
}