无法将 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

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

Cannot convert void to java.lang.Void

javalambdajava-8

提问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::updatecannot 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 Functionreturns a value, even if it is declared as being of type Void(you will have to return nullthen. In contrast, a voidmethod really returns nothing, not even null. So you have to insert the returnstatement:

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.Consumerinterface. 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
}