Groovy - 关闭vs方法 - 差异 [英] Groovy - closures vs methods - the difference
问题描述
如果你仔细查看包含的图片,您会注意到您可以使用Eclipse IDE重构Groovy代码,并将方法转换为闭包,反之亦然。那么,封闭又是什么?它与方法有什么不同?有人能给出一个使用闭包的好例子,以及为什么它是一个有用的功能?匿名内部类不够好?
Closure是一个 Closure类实例调用逻辑。
它可以作为参数传递或分配给一个变量。它也有一些关于范围变量访问和委托调用的逻辑。
方法是普通的Java方法。没什么特别的。
是的,匿名内部类有很多样板代码来执行简单的操作。
比较:
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.dispose();
}
}
);
vs
button.addActionListener {frame.dispose()}
在SO上有一个相关的问题 Groovy:闭包或方法
和3条包含大量用户指南的链接有用的信息。
- http ://groovy.codehaus.org/Closures
- http://groovy.codehaus.org/Closures+-+Formal+Definition
- http://groovy.codehaus.org/Closures+-+Informal+Guide
If you look very carefully at the picture included, you will notice that you can refactor Groovy code using the Eclipse IDE and convert a method to a closure and vice versa. So, what exactly is a closure again and how is it different than a method? Can someone give a good example of using a closure as well as why it's a useful feature? Anonymous inner classes weren't good enough?
Closure is a Closure class instance, that implements Call logic. It may be passed as argument or assigned to a variable. It also has some logic concerned with scope variable accessing and delegating calls.
Methods are normal Java methods. Nothing special.
And yes, anonymous inner classes have a lot of boilerplate code to perform simple actions.
Compare:
button.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e ) {
frame.dispose();
}
}
);
vs
button.addActionListener { frame.dispose() }
There is a related question on SO Groovy : Closures or Methods and 3 links to the user guide containing a lot of useful information.
- http://groovy.codehaus.org/Closures
- http://groovy.codehaus.org/Closures+-+Formal+Definition
- http://groovy.codehaus.org/Closures+-+Informal+Guide
这篇关于Groovy - 关闭vs方法 - 差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!