我已经切换到Java7Build21,并开始收到奇怪的编译错误。例如,下面的代码片段无法编译(尽管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);但是如果我将第2行中的?替换为Object
2 Function<Object, String> function = new Function<Object, String>() {则编译成功。
我得到的错误有点神秘:
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将第2行更改为
2 Function<? extends Object, String> function = new Function<Object, String>() {没有任何效果。
我使用的是JDK 1.7.0_11-b21;它用于编译build 4。
这是javac的bug还是我的?
发布于 2013-01-21 23:39:54
我实际上可以通过改变
2 Function<?, String> function = new Function<Object, String>() {至
2 Function<? super Object, String> function = new Function<Object, String>() {这是有道理的-- function就是这里的消费者(出自臭名昭著的PECS成语)。
发布于 2013-01-21 23:31:28
方法签名为:
<F,T> Iterable<T> transform(Iterable<F> fromIterable, Function<? super F,? extends T> function) 这对类型参数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当您键入时:
Iterable<?>
Function<?, String>你说的是任何东西的可重复性,所以它可以是例如Iterable<Integer>。你也可以说Function from are to String,所以它可以是Function<String, String>。因为String不是Integer的超类,所以您没有满足(? super F)条件。
发布于 2013-01-21 23:15:50
这是因为Function<?,String>可以是Function<Object,String>、Function<String,String>或Function<Foo,String>中的任何一个。因此,您不能将对象输入到函数中是正确的,因为它实际上可能需要一个Foo。
当然,由于您有Iterable<?>,,所以您只知道Iterable输出对象,所以您只能使用Function<Object,WhatEver>来转换它。
https://stackoverflow.com/questions/14441545
复制相似问题