Javac type inference issue
Remi Forax
forax at univ-mlv.fr
Sun Aug 27 12:38:41 UTC 2023
> From: "attila kelemen85" <attila.kelemen85 at gmail.com>
> To: "compiler-dev" <compiler-dev at openjdk.org>
> Sent: Sunday, August 27, 2023 2:25:39 PM
> Subject: Javac type inference issue
> Hi,
> I'm never sure what type inference is supposed to work with or not, but I have
> an example what I find strange that it does not compile successfully:
> ```
> import java.util.*;
> public class Test {
> private static <T> void arrayMethod(List<? super T>[] args) {
> listMethod(Arrays.asList(args));
> }
> private static <T> void listMethod(List<List<? super T>> list) {
> }
> }
> ```
> I have tried this with 11.0.20, 20.0.2 and 21 RC, and all fails with this:
> > listMethod(Arrays.asList(args));
> > ^
> > required: List<List<? super T#1>>
> > found: List<List<? super T#2>>
> > reason: inference variable T#3 has incompatible bounds
> > equality constraints: List<? super CAP#1>
> > lower bounds: List<? super T#2>
> > where T#1,T#2,T#3 are type-variables:
> > T#1 extends Object declared in method <T#1>listMethod(List<List<? super T#1>>)
> > T#2 extends Object declared in method <T#2>arrayMethod(List<? super T#2>[])
> > T#3 extends Object declared in method <T#3>asList(T#3...)
> > where CAP#1 is a fresh type-variable:
> > CAP#1 extends Object super: T#2 from capture of ? super T#2
> Of course, if I explicitly specify the type argument for `Arrays.asList`, then
> it compiles fine, but I fail to see why this should not work without explicitly
> specifying the type arguments.
It's not a bug, it's how the capture works, a List<List<? super T>> is a List where each List can have a different type, but here you want a List of List with each list with the same type,
it can be approximated by
private static <T> void listMethod(List<? extends List<? super T>> list) {
}
but please, do not use an array of parametrized types List<? super T>[] in an API, because creating those are usually unsafe.
> Thanks,
> Attila
regards,
Rémi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/compiler-dev/attachments/20230827/de4d4dc7/attachment.htm>
More information about the compiler-dev
mailing list