Java lambda 返回 lambda
我试图在新的JDK 8函数式编程领域做一件看似相对基本的事情,但我无法让它工作。我有这个工作代码:
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class so1 {
public static void main() {
List<Number> l = new ArrayList<>(Arrays.asList(1, 2, 3));
List<Callable<Object>> checks = l.stream().
map(n -> (Callable<Object>) () -> {
System.out.println(n);
return null;
}).
collect(Collectors.toList());
}
}
它采用一个数字列表,并生成一个可以打印出来的函数列表。但是,显式转换为 Callable 似乎是多余的。在我看来,在IntelliJ看来也是如此。我们都同意这也应该有效:
List<Callable<Object>> checks = l.stream().
map(n -> () -> {
System.out.println(n);
return null;
}).
collect(Collectors.toList());
但是我得到一个错误:
so1.java:10: error: incompatible types: cannot infer type-variable(s) R
List<Callable<Object>> checks = l.stream().map(n -> () -> {System.out.println(n); return null;}).collect(Collectors.toList());
^
(argument mismatch; bad return type in lambda expression
Object is not a functional interface)
where R,T are type-variables:
R extends Object declared in method <R>map(Function<? super T,? extends R>)
T extends Object declared in interface Stream
1 error