'var keyword gives an error in IntelliJ (Wildcards may be used only as reference parameters)

When I write this code in IntelliJ, it gives this error:

Wildcards may be used only as reference parameters.

Here is my code

static <T extends Iterable<?>> void print(T collection) {
    for (var item : collection) {
        System.out.println(item + " ");
    }
    System.out.println();
}


Solution 1:[1]

I get the same message in IntelliJ from your code. However, the code still can be compiled and run, and works fine, so it seems to be a bug in IntelliJ.

For your specific case, your code can be simplified in such a way that avoids the imaginary problem:

static void print(Iterable<?> collection) {
    for (var item : collection) {
        System.out.println(item + " ");
    }
    System.out.println();
}

This provides the same functionality but the use of var here is not detected as a problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1