如何在Java8中为void(不是Void)方法指定函数类型?
我正在玩Java 8,以了解作为一等公民的功能。我有以下代码段:
package test;
import java.util.*;
import java.util.function.*;
public class Test {
public static void myForEach(List<Integer> list, Function<Integer, Void> myFunction) {
list.forEach(functionToBlock(myFunction));
}
public static void displayInt(Integer i) {
System.out.println(i);
}
public static void main(String[] args) {
List<Integer> theList = new ArrayList<>();
theList.add(1);
theList.add(2);
theList.add(3);
theList.add(4);
theList.add(5);
theList.add(6);
myForEach(theList, Test::displayInt);
}
}
我试图做的是使用方法引用将方法传递到方法。编译器将生成以下错误:displayInt
myForEach
src/test/Test.java:9: error: cannot find symbol
list.forEach(functionToBlock(myFunction));
^
symbol: method functionToBlock(Function<Integer,Void>)
location: class Test
src/test/Test.java:25: error: method myForEach in class Test cannot be applied to given ty
pes;
myForEach(theList, Test::displayInt);
^
required: List<Integer>,Function<Integer,Void>
found: List<Integer>,Test::displayInt
reason: argument mismatch; bad return type in method reference
void cannot be converted to Void
编译器抱怨 .我不知道如何在签名中指定函数接口的类型,以便代码编译。我知道我可以简单地将返回类型更改为,然后返回。但是,在某些情况下,可能无法更改要传递到其他地方的方法。有没有一种简单的方法可以按原样重用?void cannot be converted to Void
myForEach
displayInt
Void
null
displayInt