質問

I want to convert a List<Promise<Boolean>> into a Promise<List<Boolean>>. I know that this can be achieved using the sequence method, but I'm having some problems getting the types right.

Here is what I've tried:

First (naive) approach

List<Promise<Boolean>> foo = new ArrayList<Promise<Boolean>>;

// ... Code that loops over some other collection
// and adds multiple Promise<Boolean>s to foo

Promise<List<Boolean>> bar = Promise.sequence(foo);

This does not compile because "the argument type List<Promise<Boolean>> does not conform to formal parameter type Iterable<Promise<? extends A>>".

Second approach

Declaring the type of foo to conform to the formal parameter type as suggested by the error message above:

List<Promise<? extends Boolean>> foo = new ArrayList<Promise<Boolean>>()

As per the sub-typing rules laid out in this answer, Promise<Boolean> should be a subtype of Promise<? extends Boolean>, but I am getting a type mismatch here: "cannot convert from ArrayList<F.Promise<Boolean>> to List<F.Promise<? extends Boolean>>.

Third approach

Removing type information from instantiation of ArrayList<Promise<Boolean>>:

List<Promise<? extends Boolean>> foo = new ArrayList();

This compiles but results in a warning about unchecked conversion that I would like to get rid of: "The expression of type ArrayList needs unchecked conversion to conform to List<F.Promise<? extends Boolean>>."


What am I missing? How can I get the types to line up correctly?

役に立ちましたか?

解決

You can use this declaration instead:

List<Promise<? extends Boolean>> foo = new ArrayList<Promise<? extends Boolean>>();

Check the following answers to understand why this works:

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top