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

Time:05-15

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();
}

CodePudding user response:

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.

  • Related