mogronalol
mogronalol

Reputation: 3015

Why doesn't this generic assignment work?

I have a method like so:

<T extends ImportedGroupTxtContact> Importer<T> createImporter(Class<T> classToImport) 

In the method body this is fine:

ParseResult<? extends ImportedGroupTxtContact, ?> parseResult = new ParseResult<ImportedGroupTxtContact, ChildContactField<?>>();

Yet this is not:

ParseResult<T, ?> parseResult = new ParseResult<ImportedGroupTxtContact, ChildContactField<?>>();

This makes no sense to me, as T extends ImportedGroupTxtContact has the same upper bound as ? extends ImportedGroupTxtContact. What exactly is wrong?

Upvotes: 0

Views: 89

Answers (2)

JB Nizet
JB Nizet

Reputation: 691635

T extends ImportedGroupTxtContact. So it could be any subclass of ImportedGroupTxtContact. Let's replace that with Fruit. Apple extends Fruit. But you can't do

Basket<Apple> basket = new Basket<Fruit>();

Indeed, a Basket<Apple> only accepts apples, whereas a Basket<Fruit> accepts any kind of Fruit.

Upvotes: 3

Marko Topolnik
Marko Topolnik

Reputation: 200138

You are assigning a ParseResult<A, B> to ParseResult<T, ?> where T may or may not be equal to A, so this must fail. More precisely, T can be any subtype of A. The fact that T and the ? from your first example both have the same upper bound doesn't enter the equation here.

Upvotes: 2

Related Questions