Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this generic code compile?

Tags:

java

generics

Javac infers that T is String in method f(). Which rules in language spec lead to that conclusion?

<T> T g(){ return null; }

String f()
{
    return g();
}
like image 372
irreputable Avatar asked Feb 13 '26 11:02

irreputable


1 Answers

I suspect the compiler is effectively using section 15.12.2.8:

If the method result occurs in a context where it will be subject to assignment conversion (§5.2) to a type S, then let R be the declared result type of the method

This is treating the return statement as if it were subject to assignment conversion. For example, imagine we converted f() to:

String f()
{
    String tmp = g();
    return tmp;
}

Now as to whether it is subject to assignment conversion, section 14.17 (the return statement) contains this:

A return statement with an Expression must be contained in a method declaration that is declared to return a value (§8.4) or a compile-time error occurs. The Expression must denote a variable or value of some type T, or a compile-time error occurs. The type T must be assignable (§5.2) to the declared result type of the method, or a compile-time error occurs.

That reference to 5.2 is the "assignment conversion" section, so I guess that means the expression g() is "subject to assignment conversion", leading to that part of section 15.12.2.8 being applicable.

like image 177
Jon Skeet Avatar answered Feb 15 '26 00:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!