Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics

 
Rafi Fareen
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys,

If you are using generics, you should make sure that :


The only way to invoke that method is to pass Animal list as argument, no subtypes.
Or the other ways are to use the wildcard (extends & super, ?, conditions apply) ... but what about return type?



i saw questions that used generic methods and returned subtype of declared return type from methods.
 
Innar Made
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Rafi,

It will not compile. The compiler slaps us in the face with message something like "Type mismatch: cannot convert from List<Dog> to List<Animal>"


This however compiles and works fine:

Now we declared that this method will return a List of Animals, but now it may also contain Animal subclasses like Dog.
 
Rafi Fareen
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Innar Made wrote:Hello Rafi,

It will not compile. The compiler slaps us in the face with message something like "Type mismatch: cannot convert from List<Dog> to List<Animal>"


This however compiles and works fine:

Now we declared that this method will return a List of Animals, but now it may also contain Animal subclasses like Dog.


thanks bro, i got it ;)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic