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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With