Lambda导致编译错误"不兼容的类型"在Java 9中,用Java 8编译

时间:2017-11-13 09:18:34

标签: java lambda java-9

以下代码使用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() { }也会失败(仅限9个),即使我没有使用类型参数。

我已检查过Java 9发行说明并搜索了此行为的解释但未找到任何内容。我是否正确地认为这是JDK9中的错误,或者我错过了什么?

1 个答案:

答案 0 :(得分:7)

Oracle已将此接受为ID JDK-8191290的错误:

http://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8191290

更新:错误已关闭,评论为#34;已修复为10,未获得后退&#34;。