我无法弄清楚这些函数的返回类型是什么
fooBar()
和 barFoo()
在 Java 中并收到以下错误。
import java.util.function.Function;
class FooBar {
private void foo() {
}
private void bar(String s) {
}
public FunctionalInterface fooBar() {
return this::foo;// The type of foo() from the type FooBar is void, this is incompatible with the
// descriptor's return type: Class<? extends Annotation>
}
public Function<String, Void> barfoo() {
return this::bar;// The type of bar(String) from the type FooBar is void, this is incompatible
// with the descriptor's return type: Void
}
}
有什么方法可以返回这些函数,以便它们可以被其他函数使用吗?
将返回类型设置为
FuncionalInterface
没有帮助。
将返回类型设置为 Void
,但它与 void
不兼容
谢谢!
A
Function
有一个 <T,R>
泛型类型,您正在寻找 Runnable
(void
、void
函数)和 Consumer<T>
(void
、T
函数)。就像,
public Runnable fooBar() {
return this::foo;
}
public Consumer<String> bar() {
return this::bar;
}
存在与
void f()
和 void f(String a)
匹配的类型。它们分别是Runnable
和Consumer<String>
。
所以你的代码变成:
import java.util.function.Consumer;
class FooBar {
private void foo() {
}
private void bar(String s) {
}
public Runnable fooBar() {
return this::foo;
}
public Consumer<String> barfoo() {
return this::bar;
}
}