首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Lambda在Java 9中导致编译错误“不兼容的类型”,在Java 8中编译

Lambda在Java 9中导致编译错误“不兼容的类型”,在Java 8中编译
EN

Stack Overflow用户
提问于 2017-11-13 17:18:34
回答 1查看 725关注 0票数 19

下面的代码可以使用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

我已经将其范围缩小到myMethod的类型参数<T>;如果删除它并使用Object作为参数类型,代码将编译。将myMethod声明为static <T> void myMethod() { }也会失败(仅在9中),即使我没有使用类型参数。

我查看了Java 9发行说明,并搜索了对此行为的解释,但没有找到任何东西。我是不是认为这是JDK9中的一个bug,或者我错过了什么?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47260727

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档