📜 ⬆️ ⬇️

Weekday programmer or a rare compiler error

We have the following code:

1 class A { 2 3 private B line; 4 5 public void foo() { 6 for (Integer line : line.getElements()) { 7 8 } 9 } 10 } 11 12 class B { 13 14 List<Integer> getElements() { 15 return null; // doesn't matter 16 } 17 } 


Question: will the code be compiled?
Answer: should, but will not
')


And now we explain why.

It is clear that in line 6 eclipsing of the class field of the loop variable occurs. But, according to the specification it is not so! The funny thing is that one popular paid IDE for Java behaves correctly, and the compiler complains that getElements () is missing from line.

We read the specification:

The enhanced for statement has the form:

EnhancedForStatement:
for (VariableModifiersopt Type Identifier: Expression) Statement
It should be of an array type (§10.1), or a compile-time error occurs.
FormalParameter of the contained statement (§14.14)


For those who are too lazy to read in English:

for (VariableModifiersopt Type Identifier: Expression) Statement



The scope of a local variable declared in the Identifier extends to the Statement. Those. Expression is not covered.

Thus, field darkening should not occur here, but it does. Zasabmichen bug on this topic under the number 7139681 , but it will appear in the public access only after a couple of days.

Be careful!

PS I asked the appropriate question on the SO , waiting for updates.

PPS Java 1.6.0.26 64bit

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


All Articles