enhanced for could be better integrated with type inference
Stephan Herrmann
stephan.herrmann at berlin.de
Sat Jan 26 21:39:44 UTC 2019
Hi,
I know, JSR 335 has sailed time ago, but still I'd like to share a late find:
//---
import java.util.*;
public class X {
void testForeach1(boolean b, List<String> list) {
Iterable<String> it = b ? Collections.emptyList() : list;
for (String s : it) {
}
}
void testForeach2(boolean b, List<String> list) {
for (String s : b ? Collections.emptyList() : list) {
}
}
}
//---
Method testForeach1() compiles OK, but if you inline 'it' to yield
testForeach2() then type inference will fail, saying, e.g.:
incompatible types: Object cannot be converted to String
Did the EG back then have specific reasons, to view the collection expression as
a standalone expression? Apparently, if type inference could optionally use
String[] or Iterable<String> as the target type for the collection expression,
then more expressions could be admitted in this position, some of which would
likely make more sense than the above example :)
Just wondering,
Stephan
More information about the lambda-spec-comments
mailing list