Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Guava Optional as "naturally covariant object"

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.

like image 686
Ditz Avatar asked Dec 05 '22 19:12

Ditz


1 Answers

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.

like image 184
Kevin Bourrillion Avatar answered Mar 09 '23 01:03

Kevin Bourrillion