Why is this common code compiling?

Javac reports that T Stringin the method f(). What rules in the language specification lead to this conclusion?

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

String f()
{
    return g();
}
+3
source share
3 answers

I suspect that the compiler is using section 15.12.2.8 efficiently :

If the result of a method arises in the context in which it will undergo an assignment conversion (§5.2) to type S, then let R be the declared type of the result of the method

This processes the return statement as if it had undergone an assignment conversion. For example, imagine that we converted f()to:

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

, , 14.17 ( ) :

return , (§8.4) . T, . T (§5.2) .

5.2 " ", , , g() " ", 15.12.2.8.

+9

T String, g() f(), String. , T String, .

0

Since g is a generic method, Java indicates the type g to match the return type f.

You can see this by doing the following three functions.

class SomeClass{

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

   String f() {
      return this.<String>g();
   }

   Integer h() {
      return this.<Integer>g();
   }

   Integer i() {
      return this.<String>g();
   }
}

f and h will compile fine because it infers the type from the return type. I will not compile because the types do not match.

0
source

Source: https://habr.com/ru/post/1792868/


All Articles