0

Why is type inference not working in this particular case?

public class ClassB<O> {

public <T> T echo(T msg) {
    return msg;
}

public void doSomething(O a) {
}

public static void main() {
    // Test 1
    ClassB<Object> sampleB = new ClassB<>();
    // No compile time type error.
    // <T> and <O> are different.
    String test = sampleB.echo("");

    // Test 2
    ClassB sampleB1 = new ClassB();
    // Causes compile time type error.
    String test2 = sampleB1.echo("");
}
}

What does method return type <T> has to do with <O>?

Is compiler treating this as

String test2 = (Object) sampleB1.echo("");

instead of

String test2 = (String) sampleB1.echo("");
Chirayu Chiripal
  • 610
  • 6
  • 15

1 Answers1

1

Generics are opt-in (because they were added in Java 5, and old code still needs to work).

ClassB sampleB1 = new ClassB();  // this is a raw type

When you opt-out by using raw types you won't get any of the features, including generic type inference (your <T> on the method will just be ignored). You will get a compiler warning about better not using raw types instead.


What does method return type <T> has to do with <O>?

Nothing. You declared <T> on the method, it is only visible for that method, it is completely unrelated to the O on the class (unless you did something like <T extends O>) and it could even shadow other things (you could call it <O> as well, or even <String> -- but don't do that).

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • If `ClassB` is treated as `ClassB` why would old code not work? – Chirayu Chiripal Sep 20 '19 at 07:34
  • @ChirayuChiripal That is a good question. – Thilo Sep 20 '19 at 07:40
  • They did this to keep old code working but it instead is breaking old code because I'm trying to add `` to an existing class without changing anything else but old code is broken now because I no longer get type inference on my old code. – Chirayu Chiripal Sep 20 '19 at 07:53
  • That's not how it works :-) If you don't touch the source file, it will still compile. If you update it, you have to update it all the way (at least for that one variable). And note that these are compile-time errors, you are informed about this immediately (not find out later at runtime). This is a pretty smooth upgrade path (unlike some other languages) – Thilo Sep 20 '19 at 07:55