mercredi 18 mars 2015

Guava why toStringFunction not a generic function?

the Guava toStringFunction() has the following declaration:



public static Function<Object, String> toStringFunction() { ... }


All non-primitive roots at Object, so the function works well.


but when I try to compose it with another function, such as:



Function<Integer, Double> f1 = Functions.compose(Functions.forMap(someMap),
Functions.toStringFunction());


where someMap variable is a map< String, Double>, So i expect toStringFunction converts Integer to String and then forMap converts String to Double. But I get a compiler error:



Function<Integer, Double> f1 = Functions.compose(Functions.forMap(someMap),
^
required: Function<Integer,Double>
found: Function<Object,Double>
2 errors


My two questions are:


1.how to specifically tell the compiler that toStringFunction should be Function< Integer, String>? A simple cast will not work, and I am looking for a real composition of the two functions.



Function< Integer, String> g1 = (Function< Integer, String>)Functions.toStringFunction();

// cause error


2.Had the toStringFunction written as the following:



@SuppressWarnings("unchecked")
public static <E> Function<E, String> toStringFunction(){
return (Function<E, String>) ToStringFunction.INSTANCE;
}

// enum singleton pattern
private enum ToStringFunction implements Function<Object, String>{
INSTANCE;


// @Override public String toString(){
// return "Functions.toStringFunction()";
// }

@Override public String apply(Object o){
return o.toString();
}
}


I can specify the type:



Function<Integer, Double> f1 = Functions.compose(Functions.forMap(someMap),
Functions.<Integer>toStringFunction());


and this works fine. But what is the motivation for the version Guava team have right now?


Aucun commentaire:

Enregistrer un commentaire