首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >泛型:通配符类型的编译错误

泛型:通配符类型的编译错误
EN

Stack Overflow用户
提问于 2013-01-21 23:11:17
回答 3查看 2.2K关注 0票数 2

我已经切换到Java7Build21,并开始收到奇怪的编译错误。例如,下面的代码片段无法编译(尽管IntelliJ没有显示任何错误):

代码语言:javascript
复制
    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

代码语言:javascript
复制
    2 Function<Object, String> function = new Function<Object, String>() {

则编译成功。

我得到的错误有点神秘:

代码语言:javascript
复制
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行更改为

代码语言:javascript
复制
    2 Function<? extends Object, String> function = new Function<Object, String>() {

没有任何效果。

我使用的是JDK 1.7.0_11-b21;它用于编译build 4。

这是javac的bug还是我的?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-01-21 23:39:54

我实际上可以通过改变

代码语言:javascript
复制
2 Function<?, String> function = new Function<Object, String>() {

代码语言:javascript
复制
2 Function<? super Object, String> function = new Function<Object, String>() {

这是有道理的-- function就是这里的消费者(出自臭名昭著的PECS成语)。

票数 1
EN

Stack Overflow用户

发布于 2013-01-21 23:31:28

方法签名为:

代码语言:javascript
复制
<F,T> Iterable<T> transform(Iterable<F> fromIterable, Function<? super F,? extends T> function) 

这对类型参数F的含义是:

代码语言:javascript
复制
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

当您键入时:

代码语言:javascript
复制
Iterable<?>
Function<?, String>

你说的是任何东西的可重复性,所以它可以是例如Iterable<Integer>。你也可以说Function from are to String,所以它可以是Function<String, String>。因为String不是Integer的超类,所以您没有满足(? super F)条件。

票数 6
EN

Stack Overflow用户

发布于 2013-01-21 23:15:50

这是因为Function<?,String>可以是Function<Object,String>Function<String,String>Function<Foo,String>中的任何一个。因此,您不能将对象输入到函数中是正确的,因为它实际上可能需要一个Foo。

当然,由于您有Iterable<?>,,所以您只知道Iterable输出对象,所以您只能使用Function<Object,WhatEver>来转换它。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14441545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档