Why is this common code compiling?

<X> X foo(List<? super X> list)
{
    return null;
}
void test()
{
    List<Number> list = ...;
    String s1 = this.foo(list); // huh?
}

The last line makes no sense, how can javac resolve this?

Now the method foo()also makes no sense; it should return null, there is no other value that can be returned by the safe type. Therefore, the last line at run time will not cause any problems: assigns a null value to the String variable.

However, statically, why is the last line compiled? ( javac 1.6 u21 b06 )

+3
source share
3 answers

The code will not compile with the next version of JDK 1.6.0_22-b04. Error:

Type mismatch: cannot convert from number to string

I think your suggestion about a compiler error might be true.

0

?

, , eclipse, . . Eclipse , . , .

List<? super X> , List<X> List<Object>. . , , javac , .

+4

. <X>. foo, Number. String, Number foo(), , Number. Number String.

0
source

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


All Articles