Groovy - closures vs methods - the difference

流过昼夜 提交于 2019-12-21 03:52:51

问题


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?


回答1:


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 the following link(s) to the user guide containing a lot of useful information.

  1. 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.




回答2:


Also, as Closures are first class objects, they can be passed around, returned and manipulated. Consider:

def add = { n, m -> n + m }
def add2 = add.curry( 2 )

assert add2( 4 ) == 6

def makeAdder = { n ->
    // return a Closure
    { m -> n + m }
}
def anotherAdd2 = makeAdder( 2 )

assert anotherAdd2( 4 ) == 6



回答3:


A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable. The following link containing a lot of useful information. http://www.groovy-lang.org/closures.html



来源:https://stackoverflow.com/questions/21905550/groovy-closures-vs-methods-the-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!