Generic ype inference with lower bounded types

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Sat Jan 3 00:41:13 UTC 2015


Hi Sam,
This works in JDK 8 (I think there's even a comment in SO saying that). 
Long story short, Java 5/6/7 inference typically ignored inference 
constraints coming from lower bounds; the treatment in Java 8 is much 
more consistent - as a result this program compiles as you'd expect 
(assuming you don't use -source 7).

Maurizio

On 03/01/15 00:07, Sam Munkes wrote:
> Hi Guys,
>
> A colleague of mine recently posted the following question to 
> StackOverflow: 
> http://stackoverflow.com/questions/27652867/java-type-inference-with-lower-bounded-types
>
> Does anyone on the list have insight into why the compiler does not 
> infer lower bounded types?
>
> static class Test {
>     static <T> T pick(T one, T two) {
>         return two;
>     }
>
>     static void testUpperBound() {
>         List<? extends Integer> extendsInteger = new ArrayList<>();
>
>         // List<? extends Integer> is treated as a subclass of List<? 
> extends Number>
>         List<? extends Number> extendsNumber = extendsInteger;
>
>         // List<? extends Number> is inferred as the common superclass
>         extendsNumber = pick(extendsInteger, extendsNumber);
>     }
>
>     static void testLowerBound() {
>         List<? super Number> superNumber = new ArrayList<>();
>
>         // List<? super Number> is treated as a subclass of List<? 
> super Integer>
>         List<? super Integer> superInteger = superNumber;
>
>         // The inferred common type should be List<? super Integer>,
>         // but instead we get a compile error:
> *superInteger = pick(superNumber, superInteger);*
>
>         // It only compiles with an explicit type argument:
>         superInteger = Test.<List<? super Integer>>pick(superNumber, 
> superInteger);
>     }
> }
>
>
> Thanks
>
> --
> Sam

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/compiler-dev/attachments/20150103/901f0746/attachment-0001.html>


More information about the compiler-dev mailing list