What is the exact definition of a closure?

后端 未结 8 1131
执念已碎
执念已碎 2020-11-28 09:43

I\'ve read through previous topics on closures on stackflow and other sources and one thing is still confusing me. From what I\'ve been able to piece together technically a

8条回答
  •  青春惊慌失措
    2020-11-28 09:53

    Great question! Given that one of the OOP principles of OOP is that objects has behavior as well as data, closures are a special type of object because their most important purpose is their behavior. That said, what do I mean when I talk about their "behavior?"

    (A lot of this is drawn from "Groovy in Action" by Dierk Konig, which is an awesome book)

    On the simplest level a close is really just some code that's wrapped up to become an androgynous object/method. It's a method because it can take params and return a value, but it's also an object in that you can pass around a reference to it.

    In the words of Dierk, imagine an envelope that has a piece of paper inside. A typical object would have variables and their values written on this paper, but a closure would have a list of instructions instead. Let's say the letter says to "Give this envelope and letter to your friends."

    In Groovy: Closure envelope = { person -> new Letter(person).send() }
    addressBookOfFriends.each (envelope)
    

    The closure object here is the value of the envelope variable and it's use is that it's a param to the each method.

    Some details: Scope: The scope of a closure is the data and members that can be accessed within it. Returning from a closure: Closures often use a callback mechanism to execute and return from itself. Arguments: If the closure needs to take only 1 param, Groovy and other langs provide a default name: "it", to make coding quicker. So for example in our previous example:

    addressBookOfFriends.each (envelope) 
    is the same as:
    addressBookOfFriends.each { new Letter(it).send() }
    

    Hope this is what you're looking for!

提交回复
热议问题