【问题标题】:The target type of this expression must be a functional interface: Function vs Consumer此表达式的目标类型必须是函数式接口:Function vs Consumer
【发布时间】:2021-01-07 23:25:40
【问题描述】:

代码 1: 中没有错误并且可以正常工作。 代码 2 有提到的编译时错误。

问题 1: 为什么?

问题 2: 我们如何在代码 2 中返回一个函数?

代码 1:

static <T> Consumer<T> m1(Consumer<T> consumer) {
    Consumer<T> c = obj -> {
        consumer.accept(obj);

    };
    return c;
}

代码 2:

static <T, R> Function<T, R> m2(Function<T, R> f) {
    // Compile Error: The target type of this expression must be a functional interface
    Function<T, R> o = {x -> {
        f.apply(x);
    }};
    return o;

}

【问题讨论】:

    标签: java eclipse generics lambda


    【解决方案1】:

    在代码 2 中,我在 Eclipse 中遇到了您的错误,这没有帮助。在命令行上编译时,出现此错误:

    J.java:28: error: illegal initializer for Function<T,R>
                    Function<T, R> o = {x -> {
                                       ^
      where T,R are type-variables:
        T extends Object declared in method <T,R>m2(Function<T,R>)
        R extends Object declared in method <T,R>m2(Function<T,R>)
    J.java:28: error: lambda expression not expected here
                    Function<T, R> o = {x -> {
                                        ^
    2 errors
    

    你的牙套是不必要的。外面的一对大括号试图创建一个数组初始化器,而不是一个 lambda 表达式。内部大括号确实会尝试创建 lambda 表达式,但这不能在数组初始化程序中完成。

    您可以将表达式作为 lambda 表达式的返回类型,无需任何大括号。试试:

    Function<T, R> o = x -> f.apply(x);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多