From stephan.herrmann at berlin.de Sat Jan 26 21:39:44 2019 From: stephan.herrmann at berlin.de (Stephan Herrmann) Date: Sat, 26 Jan 2019 22:39:44 +0100 Subject: enhanced for could be better integrated with type inference Message-ID: <2c52a58c-f066-b374-47b8-60a6e71fce84@berlin.de> 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