• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

To understand why type erasure doesn't work with this generic method

 
Ranch Hand
Posts: 84
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys. My question is very simple, I'd like to know what's going on behind de scenes to understand why in this case type erasure is not working:



I was expecting that <T> was turn into String and compiler allows me to make it.

The error that I get is:
error: incompatible types: String cannot be converted to T

The only way that I see possible to make it is passing the String as parametter of make and make() receiving T and then returning that parameter, that's clear but I'm interesting to know why the first case is not working.

Thanks!
 
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Pablo Napoli wrote:I was expecting that <T> was turn into String and compiler allows me to make it.


That is correct, at line 7.  Where you write "Test.<String>make()", the compiler understands that for that method invocation, T is String, and therefore the expression you wrote will return a String.  That's fine, for line 7.

However, for lines 2-4 where you declare the make() method, those are outside the scope of your <String>  mentioned at line 7.  In that context, T could be anything.

I'm not really sure how to "make it work" here since I don't know what you're really trying to do.  If you want to make a method that will always return a String, just declare it as a method that returns a String.  There's not really a way to make it generic with T there.
 
Pablo Napoli
Ranch Hand
Posts: 84
2
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Mike!. I got it, this is related to the scope. Just I thought in this example because now I'm studying Generics for my next ocp exam.

Cheers!, Pablo.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic