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.
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.
posted 3 weeks ago
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.
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