【发布时间】:2021-06-14 22:01:41
【问题描述】:
我有这个代码:
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
class B { }
class C extends B { }
class D { }
class Test {
void test() {
List<B> lb = new ArrayList<B>();
List<C> lc = new ArrayList<C>();
Iterable<B> it = lb == null ? lc : lb; // a
FluentIterable.from(lb == null ? lc : lb).transform(new Function<B, D>() { // b
@Override
public D apply(B b) {
return null;
}
});
}
}
在 Java 8 行 //b 下给我这些编译器错误:
Incompatible types. Found: 'java.util.List<C>', required: 'java.util.List<capture<? extends B>>'
Incompatible types. Found: 'java.util.List<B>', required: 'java.util.List<capture<? extends B>>'
在 Java 6 下,同一行编译正常。
行//a
Iterable<B> it = lb == null ? lc : lb;
产生编译错误
Incompatible types. Found: 'java.util.List<C>', required: 'java.lang.Iterable<B>'
在 Java 6 和 Java 8 下都是正确的。
但 Guava 的 FluentIterable.from 只是 Iterable 的包装。为什么它在 Java 6 下不产生任何错误,而在 Java 8 下却产生错误?它与我在 //a 行的内容有何不同?
谢谢。
【问题讨论】:
-
Line
a应该是Iterable<? extends B> it = lb == null ? lc : lb;然后它将等同于 Java 6 为 lineb推断的内容。 -
@Holger 谢谢,我不太明白为什么 Java 8 会出错,而 Java 6 不会在 b 行。你能给我点提示吗?
-
我也不明白。规则非常复杂,并且由于目标类型的合并而发生了变化。但由于此时没有可用的目标类型,我希望它的行为类似于 Java 6。
标签: java-8 compiler-errors guava iterable java-6