Casting a constant with a common pattern

I use a static use method that returns a completed future with an 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 efficiency, I want to return the same permanent instance of the completed CompletableFuture- EMPTY_FUT , but cannot pass it in CompletableFuture<Optional<T>>because of the unlimited template.

Of course, I want to call this completed future method for any type almost the same as Optional.empty () and CompletedFuture.completedFuture (U)

How to use a generic with an unlimited template for a specific type? Is it possible at all?

+4
source share
1 answer

CompleteableFuture, , :

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

Source: https://habr.com/ru/post/1694045/


All Articles