Win a copy of Reactive Streams in Java: Concurrency with RxJava, Reactor, and Akka Streams this week in the Reactive Progamming forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Ganesh Patekar

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

 
Ranch Hand
Posts: 62
2
  • Mark post as helpful
  • send pies
  • 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!
 
Rancher
Posts: 3371
31
  • Mark post as helpful
  • send pies
  • 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: 62
2
  • Likes 2
  • Mark post as helpful
  • send pies
  • 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.
 
Catch Ernie! Catch the egg! And catch this tiny ad too:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!