Groovy - 闭包与方法 - 区别

标签 groovy closures anonymous-inner-class

enter image description here

如果您仔细查看包含的图片,您会注意到您可以使用 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 上有一个相关问题
以及以下指向用户指南的链接,其中包含许多有用的信息。
  • http://groovy-lang.org/closures.html

  • 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/

    相关文章:

    java - 有没有办法在groovy中自动设置字符串中的Windows路径?

    date - Groovy 无法将字符串解析为日期

    javascript - 我不明白为什么 Greasemonkey 脚本中的 GM_xmlhttpRequest 的 URL 不会改变

    java - 实际中如何使用内部类

    java - 克服匿名类中的最终变量

    java - 匿名内部类实际上不是子类吗?

    grails - 在Grails中创建域关系会返回无法解决的类错误

    grails - 迭代可能是字符串或字符串数​​组的 Groovy 对象

    rust - 在字符串上创建闭包返回迭代器

    closures - 引用其他闭包的存储闭包