min*_*das 2 java generics guava java-7
我已经切换到Java 7 build 21并开始出现奇怪的编译错误.例如,下面的代码片段无法编译(尽管IntelliJ不显示任何错误):
1 Iterable<?> parts = ImmutableList.<String>of("one", "two");
2 Function<?, String> function = new Function<Object, String>() {
3 @Override
4 public String apply(final Object input) {
5 return input.toString();
6 }
7 };
8 Iterable<String> result = Iterables.transform(parts, function);
9 System.out.println(result);
Run Code Online (Sandbox Code Playgroud)
但如果我?在第2行更换Object
2 Function<Object, String> function = new Function<Object, String>() {
Run Code Online (Sandbox Code Playgroud)
然后编译成功.
我得到的错误有点神秘:
error: method transform in class Iterables cannot be applied to given types;
required: Iterable<F>,Function<? super F,? extends T>
found: Iterable<CAP#1>,Function<CAP#2,String>
reason: no instance(s) of type variable(s) F,T exist so that argument type Function<CAP#2,String>
conforms to formal parameter type Function<? super F,? extends T>
where F,T are type-variables:
F extends Object declared in method <F,T>transform(Iterable<F>,Function<? super F,? extends T>)
T extends Object declared in method <F,T>transform(Iterable<F>,Function<? super F,? extends T>)
where CAP#1,CAP#2 are fresh type-variables:
CAP#1 extends Object from capture of ?
CAP#2 extends Object from capture of ? extends Object
Run Code Online (Sandbox Code Playgroud)
改变第2行
2 Function<? extends Object, String> function = new Function<Object, String>() {
Run Code Online (Sandbox Code Playgroud)
没有效果.
我正在使用JDK 1.7.0_11-b21; 这用于编译与构建4的确定.
这是一个javacbug还是我的?
方法签名是:
<F,T> Iterable<T> transform(Iterable<F> fromIterable, Function<? super F,? extends T> function)
Run Code Online (Sandbox Code Playgroud)
这对于类型参数F的意义是:
Iterable<F> :
F can be any type here, but will influence the type parameter to Function
Function<? super F, ? extends T> :
the first type parameter (? super F) MUST be a supertype of F
Run Code Online (Sandbox Code Playgroud)
键入时:
Iterable<?>
Function<?, String>
Run Code Online (Sandbox Code Playgroud)
你说任何东西都可以,所以它可以是例如Iterable<Integer>.你也说从任何东西到String的函数,所以它可能是例如Function<String, String>.由于String不是Integer的超类,因此您无法满足(? super F)条件.