That’s Groovy!

Last updated on April 11, 2024

Ask me a month ago regarding my choice of scripting language, my answer would have been Perl or, if it’s a trivial use case, Bash. That’s no longer the case. Now, I am eager to flex my Groovy knowledge.

Why Groovy?

Consider the use case of executing a system command and redirecting the output to be processed by your program. With Perl, this is a trivial task: just use a backquote to perform your system command. Perl will assign the result of your standard out to the left-hand variable.

$output = `ls -l`;
print $output, "\n";

In Groovy, it’s just as easy.

def process = "ls -l".execute()
println "${process.text}"

Now, imagine having to perform this in Java:

try {
  StringBuffer stdout = new StringBuffer();
  Process p = Runtime.getRuntime().exec( "ls -l" );

  BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()) );
  while ((line = in.readLine()) != null) {
    stdout.append(line);
  }
  in.close();
}
catch (Exception e) {
  // ...
}

Did I get your attention? I hope so. Let’s consider list. I think Groovy is better at list than Perl. Take the use case of sorting a list of numbers. In Perl, it would look akin to this.

@list = (1, 23, 4, 6, 12, 5, 36);
@sortedlist = sort {$a <=> $b} @list;
print "@sortedlist ";

In Groovy, it’s even shorter

def list = [1, 23, 4, 6, 12, 5, 26]
println list.sort()

Lists are easier to work with in Groovy. If you want to print a sub-range, it’s “println list[1..3]”. If you want the last 3 items in the array in reverse order, it’s “println list[-3..-1]”. Negative index tell Groovy to retrieve the item from tail and work its way back.

If you’re a Java developer, how can you not love Groovy.

Like Java, Love Groovy

Groovy is built on Java. It brings dynamic typing and the benefits of dynamic language to the world of Java but still provides static typing when needed. Because it’s built on Java, Groovy has access to all the Java API available in your classpath. By default, the following classes are exposed to Groovy:

  • java.io.*
  • java.lang.*
  • java.math.BigDecimal
  • java.math.BigInteger
  • java.net.*
  • java.util.*

If you need a class not imported by default, if it’s in the classpath, Groovy can use them. You can import them in or use the fully qualifying classname:

println java.sql.Date.valueOf("2013-12-31").getTime()

As stated earlier, all of Java libraries are at your disposal. Short of sounding like an infomercial, that’s not all! You can compile Groovy program and it will become accessible from Java. Consider having to write a simple POJO. Sure, you can use most IDEs to generate your getters and setters, but with Groovy, this can be simplified.

package com.jstrgames.groovy.example

class Book {
  String title
  String author

  String toString() { "${title} ${author}" }
}

Once compiled by Groovy compiler, com.jstrgames.groovy.example.Book can be accessed from any Java program. It will also automatically create all your getters and setters for each property: getTitle(), setTitle(), getAuthor(), and setAuthor(). If you want to use this class in Groovy, you can directly access the properties:

def book = new Book( title: "Groovy by Action", author: "Dierk Koenig" )
println book

def myBook = new Book()
myBook.title = "Tech Genre"
myBook.author = "John Ra"
print myBook

You can clearly see an increased productivity building modules/application/APIs with Groovy. If you want to learn more, I highly recommend reading Groovy by Action by Dierk Koenig.