def tellFortunes(closure) {
Date date = new Date("11/15/2007")
//closure date, "Your day is filled with ceremony"
//closure date, "They're features, not bugs"
// You can curry to avoid sending date repeatedly
postFortune = closure.curry(date)
postFortune "Your day is filled with ceremony"
postFortune "They're features, not bugs"
}
tellFortunes() { date, fortune ->
println "Fortune for ${date} is '${fortune}'"
}
From "Programming Groovy" pps 92-93
Result is:
Fortune for Thu Nov 15 00:00:00 EST 2007 is 'Your day is filled with ceremony'
Fortune for Thu Nov 15 00:00:00 EST 2007 is 'They're features, not bugs'
- Basically tellFortunes() accepts date and fortune as parameters, defines a code block which prints the message with the date and fortune in it
- This calls postFortune(closure) accepting the code block (called a Closure in Groovy)
- the first use of postFortune binds the date to the inbound closure and holds a reference in postFortune
- the next two postFortunes pass the string (and the date by use of curry) to the code block thus printing the message each time
No comments:
Post a Comment