Java J2EE Portal
Enterprise Java Station
J2EE curve
Java News / Articles
Java News / Articles
Integrating and Interoperating between J2EE and .NET Solutions
India Java User Groups
Creating a new Google Web Toolkit (GWT) application
Processing...
Buy Java, Deals On Software Technology Store
Click here for great deals on computers, laptops, software and books
Groovy bridges the scripting and the enterprise Java worlds PDF Print
Written by Content Team   
Apr 06, 2006 at 06:26 AM
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:

GroovySwing

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.




Add This Feed Button

Enter your Email


Java Expert Interviews
PatrickLightBodyWebWork
Struts Action Framework 2.0 should be released by August 2006
RoelStalmanOracleJDeveloper
JDeveloper is the most comprehensive Java IDE available
TitusBrown
Test Driven Development doesn't fit my brain
Processing...
Go to top of page  Home |
SiteMap

Copyright 2004 to 2008 Rightrix Solutions. All rights reserved. All product names are trademarks of their respective companies. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. Rightrix Solutions and IndicThreads.com are independent of Sun Microsystems, Inc.

Views expressed at IndicThreads.com reflect the views of the authors alone, and do not necessarily reflect those of IndicThreads.com. IndicThreads.com and it's authors are not responsible for reader comments and opinions.

Enterprise Java J2EE JEE Portal >> IndicThreads.com