问题
The new Guava 10 Optional states to be naturally covariant and thus may be casted.
If I try so it looks a bit ugly:
Optional<Integer> opti = Optional.of(42);
Optional<Number> optn = (Optional) opti;
I like to see some utility function like:
static <T> Optional<T> transform(Optional<? extends T> opt, Class<T> clazz);
(how to express this as a member function of Optional ?)
Is it even possible to define a transformation function object like:
static <T> Function<Optional<? extends T>, Optional<T>>
transformer(Class<T> class);
in order to transform a Collection<Optional<Double>> into a Collection<Optional<Number>> without creating new objects for each?
I think even the returned Function object may be realized by an internal singleton.
回答1:
Even though casting is actually even uglier than you think:
Optional<Integer> opti = Optional.of(42);
@SuppressWarnings("unchecked") // safe covariant cast
Optional<Number> optn = (Optional) opti;
... we still think it is exactly what you should do, and have ruled out providing a method like you ask for.
It's okay that it's a little cumbersome because you should very rarely need to do a thing like this, so long as you are using wildcards correctly in your API signatures, as covered in Effective Java.
回答2:
By specifying the type of the of method, you can avoid the cast entirely:
Optional<Number> optx = Optional.<Number>of(42);
来源:https://stackoverflow.com/questions/7848789/how-to-use-guava-optional-as-naturally-covariant-object