如果您仔细查看包含的图片,您会注意到您可以使用 Eclipse IDE 重构 Groovy 代码并将方法转换为闭包,反之亦然。那么,闭包到底是什么,它与方法有什么不同呢?有人可以举一个使用闭包的好例子以及为什么它是一个有用的特性吗?匿名内部类还不够好?
最佳答案
闭包是 闭包类实例 ,实现调用逻辑。
它可以作为参数传递或分配给变量。它还有一些与范围变量访问和委托(delegate)调用有关的逻辑。
方法是普通的 Java 方法。没什么特别的。
是的,匿名内部类有很多样板代码来执行简单的操作。
比较:
button.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e ) {
frame.dispose();
}
}
);
对比
button.addActionListener { frame.dispose() }
SO Groovy : Closures or Methods 上有一个相关问题
以及以下指向用户指南的链接,其中包含许多有用的信息。
A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable. A closure may reference variables declared in its surrounding scope. In opposition to the formal definition of a closure, Closure in the Groovy language can also contain free variables which are defined outside of its surrounding scope. While breaking the formal concept of a closure, it offers a variety of advantages which are described in this chapter.
关于Groovy - 闭包与方法 - 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21905550/