|
Page 3 of 5 IndicThreads >> “Closure Support” is listed as Groovy's first feature on the Groovy site. Could you tell us what are closures, maybe with an example?
Guillaume Laforge >> Closures are just reusable and assignable blocks of code. That’s a concept which unfortunately doesn’t exist in Java today. If I had only one feature request for Java, that would be to support closures natively!
"Closures are just reusable and assignable blocks of code..."
In Groovy, a closure just looks like a block of statements delimited with curly braces. So for example, the following line is a closure:
{ println "hello" }
But you can also assign this closure to a variable:
def helloClosure = { println "hello" }
Then you can call this closure as if it were a normal method:
helloClosure() // and it’ll print hello
You can pass parameters to a closure:
def printer = { msg -> println "your message is: $msg" }
Then you can call and reuse this printer closure:
printer( "hello" )
printer( "Groovy!" )
But let’s see a more useful example now. Say you have a list of things you want to filter:
def myNumbers = [1, 2, 3, 4, 5]
def criteria = { it > 3 } // ‘it’ is an implicit parameter
def result = myNumbers.findAll( criteria )
You can pass a criteria to the findAll() method on list to find all the numbers greater than 3. You can use anonymous closures too:
def result = myNumbers.findAll { it > 3 }
In Java, you have a few lines of boilerplate code to do such a simple thing as filtering a collection! In Groovy, it can be a single line.
Closures give you more expressivity to your code by allowing you to reuse snippets of code to manipulate collections and many other things.
IndicThreads >> Currently there are several scripting languages floating around, each with its set of experts saying that scripting language X is the future. That only makes developers unsure, and they end up staying away from all the languages. What is Groovy's USP?
Guillaume Laforge >> I think Groovy’s biggest selling point is its MOP (its Meta-Object Protocol). That’s not the most widely known aspect of Groovy, but in conjunction with closures, you can do really cool things. From these two things, we’ve built the concept of “builders”.
"Groovy’s biggest selling point is its MOP (its Meta-Object Protocol)..."
Builders let you build complex structures very easily. Let’s see that with some examples, since a few lines of code are often worth thousand words:
A markup builder:
new MarkupBuilder().html {
head { title "Groovy in Action" }
body {
['red', 'green', 'blue'].each {
p(style:"color:$it", "Groovy rocks!")
}
}
}
You can mix and match markup code as well as normal Groovy code, and it’ll print:
Groovy in Action
Groovy rocks!
Groovy rocks!
Groovy rocks!
We’ve got a Swing builder that lets you create GUIs:
def theMap = [color: "green", object: "pencil"]
def swing = new SwingBuilder()
def frame = swing.frame(
title: 'A Groovy Swing',
location: [240,240],
defaultCloseOperation:WindowConstants.EXIT_ON_CLOSE) {
panel {
for (entry in theMap) {
label(text: entry.key)
textField(text: entry.value)
}
button(text: 'About', actionPerformed: {
def pane = swing.optionPane(message: 'SwingBuilder')
def dialog = pane.createDialog(null, 'About')
dialog.show()
})
button(text:'Quit', actionPerformed:{ System.exit(0) })
}
}
frame.pack()
frame.show()
And you’ll get a quick GUI like the following screenshot shows:

More generally, the MOP lets you manipulate the language itself to let you build your own language structures, or your own “Domain Specific Language”. Only “dynamic” languages can do that kind of things. Simple scripting languages can’t do that. That’s where Groovy particularly shines.
|