var 关键字在 IntelliJ 中给出错误(通配符只能用作参考参数)

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

当我在 IntelliJ 中编写此代码时,出现以下错误:

Wildcards may be used only as reference parameters.

这是我的代码

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

我在 IntelliJ 中从您的代码中得到了同样的信息。但是,代码仍然可以编译和 运行,并且工作正常,所以它似乎是 bug in IntelliJ.

对于您的具体情况,您的代码可以通过避免想象中的问题的方式进行简化:

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

这提供了相同的功能,但未检测到此处使用 var 有问题。