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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26828246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:42:57  来源:igfitidea点击:

Why can't I assign lambda to Object?

javajava-8

提问by texasbruce

I was trying to assign a lambda to Object type:

我试图将 lambda 分配给 Object 类型:

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?

为什么会发生这种情况,以及如何做到这一点?

回答by Reimeus

It's not possible. As per the error message Objectis not a functional interface, that is an interface with a single public method so you need to use a reference type that is, e.g.

这是不可能的。根据错误消息Object不是功能接口,这是一个具有单个公共方法的接口,因此您需要使用引用类型,例如

Runnable r = () -> {}; 

回答by Thiago Negri

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. It's just syntax sugar.

当编译器看到 lambda 表达式时,它会尝试将其转换为您尝试定位的函数式接口类型的实例。这只是语法糖。

The compiler can only convert lambda expressions to types that have a single abstract method declared. This is what it calls as "functional interface". And Objectclearly does not fit this.

编译器只能将 lambda 表达式转换为声明了单个抽象方法的类型。这就是它所谓的“功能接口”。而且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. Essentially, it is the same thing as writing:

然后 Java 将能够将 lambda 表达式转换为扩展Runnable. 本质上,它与写作是一样的:

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 Runnabletype because of the type signature of f. But, there is no "lambda type" in Java world.

Java可以推断兰巴表达式必须的Runnable类型,因为类型的签名f。但是,Java 世界中没有“lambda 类型”。

If you are trying to create a generic function that does nothing in Java, you can't. Java is 100% statically typed and object oriented.

如果您正在尝试创建一个在 Java 中什么都不做的通用函数,则不能。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 表达式之间存在一些差异,但您可以查看它们,因为它们只是用于使用单个抽象方法实例化类型对象的语法糖。