Local variable inference and anonymous class

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Thu Nov 16 17:33:00 UTC 2017

FTR, this is not just about lambdas and Java 8 in general, this behavior 
is there since inner classes were added:

String s = new Object() { String s }.s;

and, after Java 5:

<Z> id(Z z) { return z; }

String s = id(new Object()).s;

And then of course in Java 8 the inference enhancement allows for these 
types to propagate in a stream method chain.

But yes - bottom line is - these types are not new, and they have been 
available for a long time - albeit the places in which they have been 
exposed have been relatively limited so far.


On 15/11/17 22:15, Remi Forax wrote:
> I had to persuade myself that the fact that a var with an anonymous class will 'leak' the anonymous type [1] is not an issue.
> By example, with
>    var foo = new Object() { int i; };
> the type of foo is the anonymous class and not Object.
> In fact, we can already 'leak' the type of an anonymous class using a lambda that creates an anonymous class,
> to create a kind of strawman tuple:
>      List<String> list = List.of("hello", "world!");
>      Map<Integer, String> map = list.stream()
>        .map(s -> new Object() { int key = s.length(); String value = s; })
>        .collect(Collectors.toMap(t -> t.key, t -> t.value));
>      System.out.println(map);
> so i guess 'leaking' the type of an anonymous class is not an issue.
> BTW, Eclipse doesn't compile the code above, but this is reported as a bug.
>    https://bugs.eclipse.org/bugs/show_bug.cgi?id=477894
> regards,
> Rémi
> [1] http://cr.openjdk.java.net/~dlsmith/local-var-inference.html

More information about the amber-spec-experts mailing list