Keyur Jain
Keyur Jain

Reputation: 13

Java : CompletableFuture<?> Capturing

I have a variable CompletableFuture<?> completableFuture. I want to be able to complete it with object of any type. For example : completableFuture.complete(new String("Hello")) or something else. This is a design requirement for my project. But I am getting the following error : complete (capture<? extends java.lang.Object>) in CompletableFuture cannot be applied to (java.lang.String[])

I know the issue is something related to capturing wildcards in Java but I cannot find a well-explained solution to this problem on the internet that helps me out.

Can you please tell me a way to complete my CompletableFuture with any object.

Upvotes: 0

Views: 655

Answers (1)

ernest_k
ernest_k

Reputation: 45319

You can use a CompletableFuture<Object>, which will accept any type:

CompletableFuture<Object> completableFuture = ...;
completableFuture.complete(new Object());
completableFuture.complete("abc");
completableFuture.complete(new String[] { "abc" });
completableFuture.complete(null);
completableFuture.complete(new ArrayList<String>());

The problem is that CompletableFuture<?> is compatible with many concrete generic types, suh as CompletableFuture<String>, CompletableFuture<String[]>. And that's why the compiler prohibits calls like completableFuture.complete(String[]) (potential for calling complete with incompatible types).

The alternative would be to declare your completable future as CompletableFuture<? super Object>, but doesn't make much sense, does it?

Upvotes: 1

Related Questions