无法将 void 转换为 java.lang.Void
Cannot convert void to java.lang.Void
我正在尝试执行以下操作
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
不能用作Function<String, Void>
。
当然不能写Function <String, void>
,我也不想把update()
的return类型改成Void
。
如何解决这个问题?
A Function
return 是一个值,即使它被声明为 Void
类型(你必须 return null
然后。相比之下,void
方法实际上 return 什么都没有,甚至 null
也没有。所以你必须插入 return
语句:
void update(Collection<String> values, Updater updater) {
update(values, s -> { updater.update(); return null; }, 0);
}
另一种方法是将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
}
一个函数return是一个值。您正在寻找的是 java.util.function.Consumer
界面。这有一个 void accept(T)
方法并且没有 return 值。
所以你的方法变成了:
void update(Collection<String> values, Consumer<String> fn, int ignored) {
// some code
}
我正在尝试执行以下操作
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
不能用作Function<String, Void>
。
当然不能写Function <String, void>
,我也不想把update()
的return类型改成Void
。
如何解决这个问题?
A Function
return 是一个值,即使它被声明为 Void
类型(你必须 return null
然后。相比之下,void
方法实际上 return 什么都没有,甚至 null
也没有。所以你必须插入 return
语句:
void update(Collection<String> values, Updater updater) {
update(values, s -> { updater.update(); return null; }, 0);
}
另一种方法是将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
}
一个函数return是一个值。您正在寻找的是 java.util.function.Consumer
界面。这有一个 void accept(T)
方法并且没有 return 值。
所以你的方法变成了:
void update(Collection<String> values, Consumer<String> fn, int ignored) {
// some code
}