May 21, 2019
Hot Topics:

Your Way to Groovy

  • January 27, 2007
  • By Koenig with Glover, King, Laforge and Skeet
  • Send Email »
  • More Articles »

Listing a file: closures and I/O additions

Closures are blocks of code that can be treated as first-class objects: passed around as references, stored, executed at arbitrary times, and so on. Java's anonymous inner classes are often used this way, particularly with adapter classes, but the syntax of inner classes is ugly, and they're limited in terms of the data they can access and change.

File handling in Groovy is made significantly easier with the addition of various methods to classes in the java.io package. A great example is the File. eachLine method. How often have you needed to read a file, a line at a time, and perform the same action on each line, closing the file at the end? This is such a common task, it shouldn't be difficult-so in Groovy, it isn't. Let's put the two features together and create a complete program that lists a file with line numbers:

def number=0
new File ('test.groovy').eachLine { line ->
println "$number: $line"

The closure in curly braces gets executed for each line, and File's new eachLine method makes this happen.

Printing a list: collection literals and simplified property access

java.util.List and java.util.Map are probably the most widely used interfaces in Java, but there is little language support for them. Groovy adds the ability to declare list and map literals just as easily as you would a string or numeric literal, and it adds many methods to the collection classes.

Similarly, the JavaBean conventions for properties are almost ubiquitous in Java, but the language makes no use of them. Groovy simplifies property access, allowing for far more readable code.

Here's an example using these two features to print the package for each of a list of classes. Note that the word package needs to be quoted because it's a keyword, but it can still be used for the property name. Although Java would allow a similar first line to declare an array, we're using a real list here-elements could be added or removed with no extra work:

def classes = [String, List, File]
for (clazz in classes)
println clazz.'package'.name

In Groovy, you can even avoid such commonplace for loops by applying property access to a list-the result is a list of the properties. Using this feature, an equivalent solution to the previous code is

println( [String, List, File].'package'.name )

to produce the output

["java.lang", "java.util", "java.io"]

Pretty cool, eh?

XML handling the Groovy way: GPath with dynamic properties

Whether you're reading it or writing it, working with XML in Java requires a considerable amount of work. Alternatives to the W3C DOM make life easier, but Java itself doesn't help you in language terms-it's unable to adapt to your needs. Groovy allows classes to act as if they have properties at runtime even if the names of those properties aren't known when the class is compiled. Gpath was built on this feature, and it allows seamless XPath-like navigation of XML documents.

Suppose you have a file called customers.xml such as this:

<?xml version="1.0" ?>
<customer name="Bill Gates" company="Microsoft" />
<customer name="Steve Jobs" company="Apple" />
<customer name="Jonathan Schwartz" company="Sun" />
<customer name="John Doe" />
<customer name="Jane Doe" />

You can print out all the corporate customers with their names and companies using just the following code. (Generating the file in the first place with Groovy using a Builder would be considerably easier than in Java, too.)

def customers = new XmlSlurper().parse(new File('customers.xml'))
for (customer in customers.corporate.customer)
println "${customer.@name} works for ${customer.@company}"

Even trying to demonstrate just a few features of Groovy, you've seen other features in the preceding examples-string interpolation with Gstring, simpler for loops, optional typing, and optional statement terminators and parentheses, just for starters. The features work so well with each other and become second nature so quickly, you hardly notice you're using them.

Although being Java friendly and feature rich are the main driving forces for Groovy, there are more aspects worth considering. So far, we have focused on the hard technical facts about Groovy, but a language needs more than that to be successful. It needs to attract people. In the world of computer languages, building a better mousetrap doesn't guarantee that the world will beat a path to your door. It has to appeal to both developers and their managers, in different ways.

Community-driven but corporate-backed

For some people, it's comforting to know that their investment in a language is protected by its adoption as a standard. This is one of the distinctive promises of Groovy. Since the passage of JSR-241, Groovy is the second standard language for the Java platform (the first being the Java language).

The size of the user base is a second criterion. The larger the user base, the greater the chance of obtaining good support and sustainable development. Groovy's user base is reasonably sized. A good indication is the activity on the mailing lists and the number of related projects (see http://groovy.codehaus.org/Related+Projects).

Attraction is more than strategic considerations, however. Beyond what you can measure is a gut feeling that causes you to enjoy programming or not. The developers of Groovy are aware of this feeling, and it is carefully considered when deciding upon language features. After all, there is a reason for the name of the language.

Someone recently stated that Groovy was, "Java-stylish with a Ruby-esque feeling." We cannot think of a better description. Working with Groovy feels like a partnership between you and the language, rather than a battle to express what is clear in your mind in a way the computer can understand.

Of course, while it's nice to "feel the groove," you still need to pay your bills. In the next section, we'll look at some of the practical advantages Groovy will bring to your professional life.


We hope that by now we’ve convinced you that you really want Groovy in your life. As a modern language built on the solid foundation of Java and with support from Sun, Groovy has something to offer for everyone, in whatever way they interact with the Java platform.

With a clear idea of why Groovy was developed and what drives its design, you should be able to see where features fit into the bigger picture as each is introduced in the next article.


¹ http://www.robert-tolksdorf.de/vmlanguages.html lists close to 200 (!) languages targeting the Java Virtual Machine.

About the Authors

Dierk Koenig is a senior software developer, mentor and coach. He publishes in leading German magazines on software development and speaks at international conferences. He works at Canoo Engineering AG, Basel, Switzerland, where he is the founding partner and member of the executive board. He joined the Groovy project in 2004 working as a committer ever since.

Andrew Glover is the President of Stelligent Incorporated which helps companies address software quality with effective developer testing strategies and continuous integration techniques that enable teams to monitor code quality early and often. He actively blogs about software quality at thediscoblog.com and testearly.com.

Dr Paul King is Managing Director and Principal Consultant for ASERT, an Australian company specialising in helping its customers leverage emerging technologies. He has provided technical and strategic consulting to hundreds of organizations throughout the U.S. and Asia Pacific and is an active contributor to many open source projects. When not being a taxi service for his seven children, you will find Paul tinkering with the latest Agile or enterprise technologies.

As the official Groovy Project Manager and member of the JSR-241 Expert Group standardizing the Groovy Scripting Language, Guillaume Laforge is a passionate Groovy developer. In his professional career, Guillaume is a software architect and Open Source consultant, working for OCTO Technology, a company focusing on architecture of software and information systems

Jon Skeet is a software engineer and inveterate technological dabbler who happens to specialise in Java and C# development. A recent convert to Groovy, Jon is fanatical about using smarter ways to write cleaner, more readable code.

Source of This Material

Groovy in Action
By Dierk Koenig with Andrew Glover, Paul King, Guillaume Laforge and Jon Skeet

Published: January, 2007, Paperback: 696 pages
Published by Manning Publications
ISBN: 1932394842
Retail price: $44.99 for the Softbound print book + PDF ebook or $25.00 for the PDF ebook both through www.manning.com.
This material is from Chapter 1 of the book.

Page 2 of 2

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date