问题
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