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 Optional upcast(Optional extends T> opt) {
return (Optional) 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
to accept an Optional extends Throwable>
.