提问人:Mradul Singhal 提问时间:7/27/2023 更新时间:7/27/2023 访问量:43
具有 void 返回类型且不采用输入参数的函数的数据类型
Data type of Function with void return type and taking no input parameters
问:
我无法弄清楚这些函数的返回类型是什么,并且在 Java 中出现以下错误。fooBar()
barFoo()
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
谢谢!
答:
0赞
Elliott Frisch
7/27/2023
#1
A 具有泛型类型,您正在寻找 (a , function) 和 Consumer<T>
(a , function)。喜欢Function
<T,R>
Runnable
void
void
void
T
public Runnable fooBar() {
return this::foo;
}
public Consumer<String> bar() {
return this::bar;
}
1赞
tgdavies
7/27/2023
#2
有匹配 和 的类型。它们分别是 和 。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;
}
}
上一个:将函数作为另一个函数的值传递
评论
Consumer<String>