How can I safely upcast an Optional? [duplicate]

荒凉一梦 提交于 2021-02-04 21:37:23

问题


Suppose I have an Optional<Exception> and want to cast it to an Optional<Throwable>. Are there any prettier ways of doing this rather than:

Optional<Exception> optionalException = Optional.of(new Exception());
Optional<Throwable> optionalThrowable = (Optional<Throwable>) (Optional<? extends Throwable>) optionalException;

This solution generates a lint warning in IntelliJ.

Unchecked cast: 'java.util.Optional<capture<? extends java.lang.Throwable>>' to 'java.util.Optional<java.lang.Throwable>'

回答1:


Found it:

Optional<Exception> optionalException = Optional.of(new Exception());
Optional<Throwable> optionalThrowable = optionalException.map(Function.identity());



回答2:


Your solution is OK, but has the downside of creating a new Optional instance.

An alternative is to write a utility method, in which you can suppress the warning just once:

@SuppressWarnings("unchecked")  // Safe covariant cast.
static <T> Optional<T> upcast(Optional<? extends T> opt) {
  return (Optional<T>) opt;
}

and then just use this in all the places without warnings.

But better (if you have the control to do so) is to fix the place where you need an Optional<Throwable> to accept an Optional<? extends Throwable>.



来源:https://stackoverflow.com/questions/61063339/how-can-i-safely-upcast-an-optional

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