Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 此表达式的目标类型必须是函数接口:函数vs使用者_Java_Eclipse_Generics_Lambda - Fatal编程技术网

Java 此表达式的目标类型必须是函数接口:函数vs使用者

Java 此表达式的目标类型必须是函数接口:函数vs使用者,java,eclipse,generics,lambda,Java,Eclipse,Generics,Lambda,在代码1中:没有错误,可以正常工作。 代码2存在上述编译时错误 问题1: 为什么? 问题2: 如何在代码2中返回函数 代码1: static <T> Consumer<T> m1(Consumer<T> consumer) { Consumer<T> c = obj -> { consumer.accept(obj); }; return c; } 静态耗电元件m1(耗电元件){ 消费者c=obj-

代码1中:没有错误,可以正常工作。 代码2存在上述编译时错误

问题1: 为什么?

问题2: 如何在代码2中返回函数

代码1:

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

    };
    return c;
}
静态耗电元件m1(耗电元件){
消费者c=obj->{
消费者接受(obj);
};
返回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;

}
静态功能m2(功能f){
//编译错误:此表达式的目标类型必须是函数接口
函数o={x->{
f、 应用(x);
}};
返回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
J.java:28:错误:函数的初始值设定项非法
函数o={x->{
^
其中T,R是类型变量:
T扩展方法m2中声明的对象(函数)
R扩展方法m2中声明的对象(函数)
J.java:28:错误:此处不需要lambda表达式
函数o={x->{
^
2个错误
大括号是不必要的。外部大括号对尝试创建数组初始值设定项,而不是lambda表达式。内部大括号确实尝试创建lambda表达式,但这不能在数组初始值设定项中完成

表达式可以是lambda表达式的返回类型,不带大括号。请尝试:

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

是的,eclipse错误没有帮助。