0

I am curious (quite new to closure). How do groovy closure knows that it should map parameter animal to the testMap's key and parameter animalSound to testMap's value?

def testMap = ['cat':'Meow', 'dog':'Woof'] testMap.each { animal, animalSound -> println "${animal} has the sound ${animalSound}" }; 

1 Answer 1

1

It's not the closure that knows, it's the implementation of the each method that is defined in java.util.Map in the Groovy JDK.

As per the documentation, the method requires that the passed in closure accept 1 or 2 arguments. Otherwise, it will throw an exception

[foo:'bar'].each { -> } // throws MissingMethodException 

The Groovy JDK is the subset of JavaSE classes (e.g. Collections API, I/O, java.lang, etc.) that have been enhanced by the Groovy language to make them more useful.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you elaborate in your answer a little bit? As it stands this is basically "because" with a link to the explanation.
Yeah, "because" isn't terribly satisfying. Think of the Closure as the receiver of the Map key and value, and the each method as the thing that is passing in the key and value to the Closure. Then the question becomes "How does the each method know to pass the key and value?" Well, because that's how they implemented the each method to work.