简体   繁体   English

为什么不能将lambda分配给Object?

[英]Why can't I assign lambda to Object?

I was trying to assign a lambda to Object type: 我试图为对象类型分配一个lambda:

Object f = ()->{};

And it gives me error saying: 它给我一个错误的说法:

 The target type of this expression must be a functional interface

Why is this happening, and how to do this? 为什么会这样,怎么做?

It's not possible. 这是不可能的。 As per the error message Object is not a functional interface, that is an interface with a single public method so you need to use a reference type that is, eg 根据错误消息, Object不是功能接口,即具有单个公共方法的接口,因此您需要使用引用类型,例如

Runnable r = () -> {}; 

This happens because there is no "lambda type" in the Java language. 发生这种情况是因为Java语言中没有“ lambda类型”。

When the compiler sees a lambda expression, it will try to convert it to an instance of the functional interface type you are trying to target. 当编译器看到lambda表达式时,它将尝试将其转换为您要定位的功能接口类型的实例。 It's just syntax sugar. 这只是语法糖。

The compiler can only convert lambda expressions to types that have a single abstract method declared. 编译器只能将lambda表达式转换为声明了一个抽象方法的类型。 This is what it calls as "functional interface". 这就是所谓的“功能接口”。 And Object clearly does not fit this. 而且Object显然不适合这个。

If you do this: 如果您这样做:

Runnable f = (/*args*/) -> {/*body*/};

Then Java will be able to convert the lambda expression to an instance of an anonymous class that extends Runnable . 然后,Java将能够将lambda表达式转换为扩展Runnable的匿名类的实例。 Essentially, it is the same thing as writing: 本质上,这与编写相同:

Runnable f = new Runnable() {
    public void run(/*args*/) {
        /*body*/
    }
};

I've added the comments /*args*/ and /*body*/ just to make it more clear, but they aren't needed. 我添加了注释/*args*//*body*/只是为了使其更清楚,但它们不是必需的。

Java can infer that the lamba expression must be of Runnable type because of the type signature of f . Java可以推断出,由于f的类型签名,lamba表达式必须为Runnable类型。 But, there is no "lambda type" in Java world. 但是,Java世界中没有“ lambda类型”。

If you are trying to create a generic function that does nothing in Java, you can't. 如果您试图创建一个在Java中不执行任何操作的通用函数,则不能。 Java is 100% statically typed and object oriented. Java是100%静态类型化和面向对象的。

There are some differences between anonymous inner classes and lambdas expressions, but you can look to them as they were just syntax sugar for instantiating objects of a type with a single abstract method. 匿名内部类和lambdas表达式之间有一些区别,但是您可以查看它们,因为它们只是用于使用单个抽象方法实例化类型的对象的语法糖。

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

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