es el compilador de Java capaz de inferir el tipo de una función estática genérica de su contexto como argumento a otra función estática genérica?inferir tipos genéricos de funciones genéricas anidadas estáticas
Por ejemplo, tengo una sencilla clase Par:
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;
}
// ...
}
y tengo la siguiente función estática genérica:
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();
}
};
que deseo utilizar de la siguiente manera (Collections2.transform is from Google Guava):
List<Pair<Integer, Double>> values = ...
Collection<Integer> firsts = Collections2.transform(values,
Pair.deferredFirst());
A los que el compilador se queja:
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>)
Parece que el compilador no puede propagar los tipos inferidos para transform() a deferredFirst() como cree que son objetos.
Forzar el compilador para entender los tipos de cualquiera de estas maneras funciona:
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());
¿Es posible cambiar la firma de cualquiera de las funciones para permitir que el compilador para inferir/propagar los tipos?
Editar: Para Bohemia, aquí hay un método posible el ejemplo anterior podría ser utilizado en:
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;
}
Tenga cuidado cuando tenga 'clase A {public void method() {}}'. Supongo que las 'F, S' en el método anulan las de tu clase (es decir, equivalente a' clase A {public
void method() {}} ' – toto2