【发布时间】:2015-01-08 11:17:06
【问题描述】:
我正在尝试在新的 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
【问题讨论】:
-
而不是强制转换,更喜欢
map(..)的显式类型参数。l.stream().<Callable<Object>> map(...)
标签: java lambda functional-programming java-8