This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics  RSS feed

 
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 ;)
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!