Fwd: enhanced for could be better integrated with type inference

Brian Goetz brian.goetz at oracle.com
Mon Jan 28 20:08:59 UTC 2019


Received on the -comments list.



> Begin forwarded message:
> 
> From: Stephan Herrmann <stephan.herrmann at berlin.de>
> Subject: enhanced for could be better integrated with type inference
> Date: January 26, 2019 at 4:39:44 PM EST
> To: lambda-spec-comments at openjdk.java.net
> 
> 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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/lambda-spec-experts/attachments/20190128/606e74bc/attachment.html>


More information about the lambda-spec-experts mailing list