How to use Guava Optional as “naturally covariant object”

半世苍凉 提交于 2019-12-10 17:14:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!