繁体   English   中英

此表达式的目标类型必须是函数接口:Function vs Consumer

[英]The target type of this expression must be a functional interface: Function vs Consumer

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

问题1 :为什么?

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

代码 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;

}

在代码 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM