以下代码可以用 Java 8 编译,但不能用 Java 9:
public class CompileErrJdk9 {
@FunctionalInterface public interface Closure<R> {
R apply();
}
@FunctionalInterface public interface VoidClosure {
void apply();
}
static <R> R call(Closure<R> closure) {
return closure.apply();
}
static void call(VoidClosure closure) {
call(() -> { closure.apply(); return null; });
}
static <T> void myMethod(T data) {
System.out.println(data);
}
public static void main(String[] args) {
call(() -> myMethod("hello")); //compile error in jdk9
}
}
这是错误:
CompileErrJdk9.java:24: error: incompatible types: inference variable R has incompatible bounds
call(() -> myMethod("hello")); //compile error in jdk9
^
upper bounds: Object
lower bounds: void
where R is a type-variable:
R extends Object declared in method <R>call(Closure<R>)
1 error
我已将其缩小到类型参数 <T>
的 myMethod
;如果我放弃它并使用 Object
对于代码编译的参数类型。声明 myMethod
作为 static <T> void myMethod() { }
即使我没有使用 type 参数,也会失败(仅在 9 中)。
我检查了 Java 9 发行说明并搜索了对此行为的解释,但没有找到任何东西。我认为这是 JDK9 中的错误是正确的,还是我遗漏了什么?
最佳答案
Oracle 已将其视为 ID JDK-8191290 的错误:
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8191290
更新:该错误已通过注释“已在 10 中修复,不会向后移植”关闭。
关于java - Lambda 在 Java 9 中导致编译错误 "incompatible types",在 Java 8 中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47260727/