How to use Guava Optional as a "naturally covariant object",

The new Guava 10 Optional states that it is naturally covariant and therefore can be launched.

If I try, it looks a little ugly:

Optional<Integer> opti = Optional.of(42); Optional<Number> optn = (Optional) opti; 

I like to see some useful function like:

 static <T> Optional<T> transform(Optional<? extends T> opt, Class<T> clazz); 

(how to express this as a member function optional?)

Is it even possible to define an object of a transformation function, for example:

 static <T> Function<Optional<? extends T>, Optional<T>> transformer(Class<T> class); 

to convert a Collection<Optional<Double>> to Collection<Optional<Number>> without creating new objects for each?

I think that even the returned Function object can be implemented using an internal singlet.

+4
source share
2 answers

Although 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 believe that this is exactly what you should do, and excluded by providing the method as you ask.

It's good that this is a little cumbersome, because you very rarely need to do something like this if you use wildcards correctly in your API signatures, as described in Effective Java.

+8
source

By setting the type of the method of , you can completely exclude the listing:

  Optional<Number> optx = Optional.<Number>of(42); 
+8
source

All Articles