无法将void转换为java.lang.Void

Kas*_*eda 20 java lambda java-8

我正在尝试做以下事情

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
}
Run Code Online (Sandbox Code Playgroud)

但我得到这个编译器错误:

"Cannot convert void to java.lang.Void"
Run Code Online (Sandbox Code Playgroud)

这意味着updater::update不能用作Function<String, Void>.

当然,我不能写Function <String, void>,我不想改变的返回类型update()Void.

我该如何解决这个问题?

Hol*_*ger 31

A Function返回一个值,即使它被声明为类型Void(null 然后你必须返回.相反,一个void方法实际上什么也不返回,甚至不返回null.所以你必须插入return语句:

void update(Collection<String> values, Updater updater) {
    update(values, s -> { updater.update(); return null; }, 0);
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是将to更改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
}
Run Code Online (Sandbox Code Playgroud)

  • @Dmitry Ginzburg:这个问题用[tag:java-8]标记,你想提出什么警告? (2认同)

Hoo*_*pje 12

函数返回一个值.您正在寻找的是java.util.function.Consumer界面.这有一个void accept(T)方法,不返回值.

所以你的方法变成:

void update(Collection<String> values, Consumer<String> fn, int ignored) {
    // some code
}
Run Code Online (Sandbox Code Playgroud)