Published in: Groovy
URL: http://hansamann.podspot.de/files/grails_podcast_episode_41.mp3
This snippet gives you some interesting examples about Groovy Closures. Listen to the audio to get the best learning experience. Simply right-click on the title above to download the mp3 file of this part of the series.
The Groovy Series is part of the Grails Podcast and can be subscribed to via: http://hansamann.podspot.de/rss. The series is produced by Dierk König and Sven Haiges, further information about the topic of this episode can be found in the book
Groovy in Action - http://groovy.canoo.com/gina
//Whenever you see the curly braces of a closure think: "new Closure(){}". //.call or just closureName() c() //as the output of this demo gets messy, we use a closure to print some separators sep() //the nice thing is you can pass closures around, just as parameters //this will print 'I am a closure' three times, as it is called //for each element. sep() //right, above code does not really make a lot of sense. The nice //thing is you can pass values to the closure. //Same example, slightly modified. It will print 1, 4, 9 sep() //as you can leave out the parenthesis and directly pass a unnamed closure, the following is identical sep() //Groovy provides a default name for a single parameter passed to a closure: it //this prints 1,2,3 sep() //note you can reuse existing methods as closure. Methods are similar to closures, they just got a "name". They can be used as //closures via the method closure operator .& class SomeClass { println "Stuff for " + userName; } } def closureFromClass = myClass.&printSomeStuff //prints Stuff for Dierk closureFromClass("Dierk") sep() //prints Stuff for Dierk, Sven, Wilma, Bill sep() //default values greeting("Hans") greeting("Michael Schumacher") sep() //closure.getParameterTypes().size() sep() sep() //Resource handling
You need to login to post a comment.
