为什么 Java Lambda 也叫 Closures

Why is Java Lambda also called Closures

我目前正在研究 Java Lambda,发现它也称为闭包。

请问为什么也叫闭包?我要技术解释。

这是两个不同的术语,恰好在同一上下文中经常被提及。

  • A lambda 基本上只是一个匿名函数。示例:() -> System.out.println("Hello")。它是一个函数,但它没有名字。

  • A 闭包 是一个关于范围界定的术语。例如,当您在 lambda 中引用局部变量时,如下所示

    int localInt = 17;
    
    saveThisFunction(() -> System.out.println(localInt));
    

    你在 lambda 中创建了一个 capture localInt 的闭包。从文本上看,很明显可以在 lambda 内部访问 localInt,但请记住,lambda 可以在 localInt 从堆栈中弹出后很长时间内存储和调用。

因此,创建 lambda 表达式通常需要(隐式)创建闭包。

仅仅是因为这些术语是等价的(我认为 "anonymous function" 也是),这就是在不同语言中调用类似机制的方式,例如Groovy 有关闭

顺便说一句,我不认为这是提出此类问题的正确选择

从技术上讲这是错误的,lambda 表达式和闭包是两个略有不同的东西。

Lambdas 是匿名函数,在 Java 世界中采用匿名单一方法 类 的形式(另请参阅 functional interfaces) :

Runnable r1 = () -> System.out.println("I'm Runnable");

闭包 是 lambda 表达式的特定子类型,其中局部变量已绑定到特定封闭环境中定义的变量。

在 Java 世界中,您只是在编写与 here 中的示例类似的内容:

final int x = 99;
        
Consumer<Integer> myConsumer = (y) -> 
{
    System.out.println("x = " + x);
    System.out.println("y = " + y);
};

更完整的闭包抽象定义:

Operationally, a closure is a data structure storing a function together with an environment: a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or storage location the name was bound to at the time the closure was created.

A closure—unlike a plain function—allows the function to access those captured variables through the closure's reference to them, even when the function is invoked outside their scope.

Source

最后一部分意味着您可以这样做:

public class Funct{


    public static Consumer<Integer> getThatClosure(){
        final int x = 99;

        Consumer<Integer> myConsumer = (y) -> 
        {
            System.out.println("x = " + x);
            System.out.println("y = " + y);
        };
        return myConsumer;
    }

    public static void main(String... args){
        Consumer<Integer> cons=getThatClosure();
        cons.accept(0);
    }

} 

有了这个输出:

x=99
y=0