Search code examples
javagenericscastingunbounded-wildcard

Cast constant generic with wildcard


I'm doing static util method which returns completed future with empty optional:

public class CompletableFutureUtils {

    private static final CompletableFuture<Optional<?>> EMPTY_FUT = completedFuture(Optional.empty());

    private static final Optional<?> EMPTY_OPT = Optional.empty();

    @Nonnull
    @SuppressWarnings("unchecked")
    public static <T> CompletableFuture<Optional<T>> emptyOptionalCompletedFuture() {

        // COMPILE ERROR: incompatible types: CompletableFuture<Optional<?>> cannot be converted to CompletableFuture<Optional<T>>
        // return (CompletableFuture<Optional<T>>)EMPTY_FUT;

        return completedFuture((Optional<T>)EMPTY_OPT); // works, but creates new instance every time
    }
}

For the sake of efficiency i want to return the same constant instance of completed CompletableFuture - EMPTY_FUT, but can't cast it to CompletableFuture<Optional<T>> because of unbounded wildcard.

Of course i want to call this completed future method for any type, pretty much the same as Optional.empty() and CompletableFuture.completedFuture(U)

How to cast generic with unbounded wildcard to specific type? Is it possible at all?


Solution

  • Cast away the type of the CompleteableFuture first, then cast again to the type you want, like this:

    return (CompletableFuture<Optional<T>>) (CompletableFuture<?>) EMPTY_FUT;