1

The following code compiles and runs just fine with Eclipse 2022-12 (4.26.0).

public static void main(String[] args) {
    List<List<?>> list = Arrays.asList(Arrays.asList("test"));
    System.out.println(test(list));
}

public static <T> T test(List<? extends List<T>> list) {
    return list.get(0).get(0);
}

However, when compiling with OpenJDK javac 19.0.2 I get the following error.

error: method test in class Test cannot be applied to given types;
        System.out.println(test(list));
                           ^
  required: List<? extends List<T>>
  found:    List<List<?>>
  reason: cannot infer type-variable(s) T
    (argument mismatch; List<List<?>> cannot be converted to List<? extends List<T>>)
  where T is a type-variable:
    T extends Object declared in method <T>test(List<? extends List<T>>)

Which compiler is correct in this case, and why? Is there a JLS that specifies that this assignment is (not) allowed? I have also read this answer. However, this doesn't help me to figure out if the assignment is allowed or not because the case of a generic type parameter T is not treated there.

Here is an example where this is relevant.

ExecutorService executorService = /* ... */;
List<Callable<?>> callables = /* ... */;
executorService.invokeAll(callables);

This code compiles with Eclipse but not with OpenJDK javac.

stonar96
  • 1,359
  • 2
  • 11
  • 39
  • Historically when the Eclipse compiler and javac disagree it *tends* to be javac that is correct, but I've seen cases in the other direction as well. Did you try with different OpenJDK versions? Even if not, please specify the exact version of both Eclipse and `javac`. – Joachim Sauer Feb 09 '23 at 15:51
  • 1
    @JoachimSauer I have added the versions to the question. I have also tried older versions (i.e. Java 17) before updating to test the latest versions of OpenJDK javac and Eclipse. – stonar96 Feb 09 '23 at 15:55
  • My gut feeling is that `javac` is correct here, since there is no correct value for `T` to infer, but I don't know the rules well enough to know for sure. Sorry. – Joachim Sauer Feb 09 '23 at 15:59
  • Yes, thanks. Assuming you are correct, an explanation with the JLS would still be interesting. – stonar96 Feb 09 '23 at 16:02

0 Answers0