【发布时间】:2014-12-06 01:13:14
【问题描述】:
考虑以下代码:
class Predicate {
public boolean eval(EvaluationContext ec) { /* logic here */ }
}
// later ...
List<Predicate> preds = new List<>( /* some predicates here */ );
// now let's use Stream<> to implement the AND logical connective:
// VERSION A:
Boolean resultA = preds.stream()
.map(p -> p.eval(context))
.reduce(Boolean.TRUE, (a,b) -> Boolean.logicalAnd(a,b));
// Oops: the code above doesn't compile ...
// Error: incompatible types: java.lang.Object cannot be converted to boolean
// VERSION B: (add an intermediate variable with explicit type)
Stream<Boolean> v = _children.stream().map(p -> p.eval(context));
Boolean resultB = v.reduce(Boolean.TRUE, (a,b) -> Boolean.logicalAnd(a, b) );
// compiles just fine...
所以,我的问题是:
版本 A 的结构有什么问题导致 Java 编译器无法正确推断 map() 的结果类型?这是 Java 中类型推断算法的限制吗?如果是这样,是否有更好的方法来编写此代码以使类型推断成功?
【问题讨论】:
-
两者都适用于 Eclipse。
-
补充说明:这里使用的是在 OpenJDK 下运行的 javac 版本 1.8.0_25。
-
你能举一个完整的例子吗? (比如没有
new List,显示_children是什么等)它也适用于1.8.0_20 Oracle JDK。 -
为了解决你的最后一个问题,我可能会使用
preds.stream().allMatch(p -> p.eval(context))。 -
在 8u25、Windows 7 x64 上为我工作。你用什么平台?另外,请添加可编译的示例。
标签: java generics compiler-errors java-8 type-inference