Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<? extends A> won't accept A's child classes

I'm working with Android Studio and I keep getting a problem I don't know how to solve. I don't know whether it's a problem with Android Studio, with Java or a mistake a make.

I have a class whose constructor is the following:

public MakeQuery(Callable<ArrayList<? extends A>) {
     ...
}

I try to create an object of that class with the following lines:

Callable<ArrayList<B>> callable = new Callable<ArrayList<B>>() {...};
MakeQuery makeQuery = new MakeQuery(callable);

(Of course, class B extends A. Double checked)

But when I call the constructor the IDE tells me that it expects another type of argument.

What mistake am I making? Thanks for all the help! :)

like image 594
Unai P. Mendizabal Avatar asked Jun 29 '15 19:06

Unai P. Mendizabal


1 Answers

Write Callable<? extends ArrayList<? extends A>>.

The reasons for this are complicated, but the code you wrote will only work if you pass in exactly Callable<ArrayList<? extends A>>.

The rule is that even if B extends A, Foo<B> does not extend Foo<A>. It does, however, extend Foo<? extends A>.

So apply that rule twice:

  1. List<B> doesn't extend List<A>, but it extends List<? extends A>.
  2. Callable<List<B>> doesn't extend Callable<List<? extends A>>, but it extends Callable<? extends List<? extends A>>.
like image 170
Louis Wasserman Avatar answered Nov 15 '22 17:11

Louis Wasserman