首页 文章

推断通用类型的嵌套静态泛型函数

提问于
浏览
11

Java编译器能否从其上下文推断泛型静态函数的类型作为另一个通用静态函数的参数?

例如,我有一个简单的Pair类:

public class Pair<F, S> {

    private final F mFirst;

    private final S mSecond;

    public Pair(F first, S second) {
        mFirst  = checkNotNull(first);
        mSecond = checkNotNull(second);
    }

    public static <F, S, F1 extends F, S1 extends S> Pair<F, S> of(F1 first, S1 second) {
        return new Pair<F, S>(first, second);
    }

    public F first() {
        return mFirst;
    }

    public S second() {
        return mSecond;
    }

    // ...
}

我有以下通用静态函数:

public static <F, P extends Pair<F, ?>> Function<P, F> deferredFirst() {
    return (Function<P, F>)DEFERRED_FIRST;
}

private static final Function<Pair<Object, ?>, Object> DEFERRED_FIRST = 
        new Function<Pair<Object,?>, Object>() {

    @Override
    public Object apply(Pair<Object, ?> input) {
        return input.first();
    }
};

我希望使用如下(Collections2.transform is from Google Guava):

List<Pair<Integer, Double>> values = ...
Collection<Integer> firsts = Collections2.transform(values, 
        Pair.deferredFirst());

编译器抱怨的内容:

The method transform(Collection<F>, Function<? super F,T>) in the type 
Collections2 is not applicable for the arguments 
(List<Pair<Integer,Double>>, Function<Pair<Object,?>,Object>)

因此,似乎编译器无法将为transform()推断的类型传播到deferredFirst(),因为它认为它们是对象 .

强制编译器以这两种方式之一理解类型:

Function<Pair<Integer, ?>, Integer> func = Pair.deferredFirst();
Collection<Integer> firsts = Collections2.transform(values, func);


Collection<Integer> firsts = Collections2.transform(values, 
        Pair.<Integer, Pair<Integer, ?>>deferredFirst());

是否可以更改任一函数的签名以允许编译器推断/传播类型?

Edit: 对于波希米亚语,这是一个可能的方法,上面的例子可用于:

public static int sumSomeInts(List<Pair<Integer, Double>> values) {
    Collection<Integer> ints = Collections2.transform(values, 
            Pair.deferredFirst());
    int sum = 0;
    for(int i : ints)
        sum += i;
    return sum;
}

3 回答

  • 1

    类型推断是令人讨厌和复杂的 . 他们不得不停在某个地方 . 考虑

    static <T> T foo();
    
    String s = foo();
    
    print( foo() )
    

    在赋值上下文中,程序员的意图是明确的, T 应该是 String

    在下一行,没有那么多 .

    print 方法不是一个非常公平的例子,它严重超载 . 假设 print 没有重载,其参数类型是固定的,因此可以清楚地推断 T . 编译器不应该足够聪明才能搞清楚吗?

    这听起来很合理,直到有人冒险阅读相关的规范文本,15.12 Method Invocation Expressions好运改变了一切乱七八糟的东西!

    它是如此复杂,甚至编译器作者都不理解它 . javac和其他编译器中存在大量错误,这些错误源于规范的这一部分 .

  • 4

    试试这个泛型功夫:

    public static int sumSomeInts(List<Pair<Integer, Double>> values) {
        Collection<Integer> ints = Collections2.transform(values, 
            Pair.<Integer, Double>deferredFirst());
        int sum = 0;
        for(int i : ints)
            sum += i;
        return sum;
    }
    

    您可以键入方法调用并将泛型传递给下一个调用 .

    我'm not sure about the exact generic parameters to use here, because you haven' t包含足够的代码 . 如果您粘贴问题所在的整个方法,我将编辑此答案以使其编译 . EDITED: with new info from question

    如果它编译,请告诉我 . 如果不是那个解决方案,那就会很接近 . 关键是使用 Class.<Type>staticMethod() 语法键入静态方法 .

  • 1

    我刚才想出的是:

    @SuppressWarnings("rawtypes")
    private static final Function ExtractFirst = new Function() {
        @Override
        public Object apply(final Object from) {
            Preconditions.checkNotNull(from);
            return ((Pair)from).first;
        }
    };
    
    @SuppressWarnings("unchecked")
    public static <A> Function<Pair<A,?>,A> extractFirst() {
        return ExtractFirst;
    }
    

    不要让“SuppressWarnings”让你失望,它运作正常 .

    例:

    List<Pair<String,String>> pairs = ImmutableList.of(Pair.of("a", "b"),
        Pair.of("c", "d"),Pair.of("e", "f"));
    Iterable<String> firsts = Iterables.transform(pairs,
        Pair.<String>extractFirst());
    

    不幸的是,您必须为extractFirst()提供泛型参数 . 我认为这是你能得到的最好的 .

相关问题