在 "lambda" 和 "anonymous classes" 的上下文中理解 Java 中的 "lambda expressions"

Understanding "lambda expressions" in Java in the context of "lambda" and "anonymous classes"

我已经阅读了大量关于 lambda 的资料。但他们是微妙的疑惑:

Q1. Definition of lambda expressions.

  1. 我没有在 oracle page 上找到明确的定义。
  2. This link 说 "A Java lambda expression is thus a function which can be created without belonging to any class."
  3. This link 说 "Lambda Expression is a concise representation of an anonymous function that can be passed around."
  4. This link 说 "Lambda expressions basically express instances of functional interfaces "

2nd 和 3rd link 没有提及函数接口。第四个 link 听起来不错,但没有说明 lambda 表达式的 "anonymous" 方面。我们能不能像这样更完美地定义它们:

Lambda expressions are "syntactically concise expressions to define anonymous implementations of functional interfaces".

我相信在定义中指定单词 "functional interface" 应该足以说明我们实现了它的唯一方法并且它的行为类似于函数,而不是 class,即使是匿名的 classes.

Q2. Do we differentiate between lambda and lambda expressions?

我觉得有区别,因为 lambda 表达式可用于定义无状态的 lambda 和有状态的闭包(即在外部词法范围内访问变量)。看来,这就是为什么 oracle link 不使用没有 "expression" 的单词 "lambda" 的原因。然而,其他 link 的情况并非如此。

Q3. This link says, with lambda expressions, "We don’t need to write a lot of boilerplate like we do for anonymous classes." Now this sounds like "Lambda expressions are like anonymous classes, its just that", "we don’t need to write a lot of boilerplate like we do for anonymous classes." I feel we cannot straight compare lambda expressions with anonymous classes, for major difference is concept anonymous class has no connection with functional interfaces, while lambda expressions are strictly dealing with functional interfaces. So anonymous classes can have any number of methods, but lambda expressions can only define single method. Am right with this?

对于问题 1,是的,您可以将其定义为日常用途。但在幕后,lambda 表达式是良好的旧方法的语法糖。看到这个 link。 lambda 的主体转换为静态方法,并且有一条invokedynamic 指令。

对于问题 2,就我而言,"lambda" 在这种情况下只是 "lambda expression" 的缩写。你不会想要在对话中使用这么长的词,对吧?在其他情况下,嗯,"lambda" 可以指代希腊字母 λ。

对于问题 3,我认为当您需要函数式接口时,lambda 表达式是编写匿名 classes 的替代方法。在较高的抽象层次上,它们都可以表示功能接口的实例。但是如果你需要一个抽象的实例 class 或一个非功能接口,那么 lambdas 就不能使用了。