What is Groovy?

Groovy is Java

If you are a bit unwilling of learning a new language, imagine you really don’t have to do that! That’s the most amazing thing about Groovy: you can start using it with just some basic experience with Java. How is that possible you ask, the answer is really simple. When you run a Groovy script it will be first compiled to the same JVM bytecode as standard Java classes and then executed by the JVM itself. Hence you can write Groovy scripts in pure Java. What is more, you will be able to use all the libraries written for Java in your scripts (i.e. Spring, Hibernate, Log4j). You have to admit that’s really cool!

What’s the big deal then?

I’m afraid that so far I might have given you the wrong impression, however it’s not like Groovy has to be just the same as Java. To get a better picture of how much Groovy can be different from what we are used to in Java I would recommend reading Features section of Groovy’s page on wikipedia which is packed with excellent snippets examples. As well you can check Differences from Java from Groovy’s official home page.

Let me give you an example as well. The below class Foo contains a map with prepopulated values and a method responsible for printing all the values from this map which are stored under a key different from the value given as a parameter to this method. First we have an implementation in Groovy and then a one in Java.

You have to admit that what we can achieve through Groovy is far more compact and readable from what we get using Java. Let me outline few key features:

  • groovy creates accessors and mutators for class parameters with no access modifier, hence no need to create the getMap() function,
  • it’s possible to create a map and populate it with values in a single line of code,
  • you don’t have to use a System.out.println call just to print some text (if you prefer using loggers check what groovy offers in this area under this adrress),
  • operators == and != implicitly call an equals method,
  • there are many helper methods for lists and maps (i.e. findAll, each) that make operating on collections easier and more readable (for the full list refer to Groovy’s documentation: here for lists and here for maps),
  • the default access modifier is public,
  • groovy allows dynamic typing – you don’t have to specify types of variables, method’s parameters and so on,
  • working with XML files has never been so easy – despite not being related to the above example this is one of my favourite feautures. Groovy makes it extremely easy to both create XML files and move around a structure of an existing one.

What’s important, is that if you don’t feel comfortable with some parts of the new syntax you don’t have to use all of them straight away. You can start writing your first Groovy scripts as you would normally create an application in Java, and then step by step introduce Groovy features that you find most useful. For instance I always leave the type of parameters in a method’s declaration as I find it far more lucid and luckily Groovy is perfectly fine with this.

Working with XML files

As I have mentioned before working with XML files in Java has never been as simple as it can be achieved in Groovy. I’m going to dedicate a separate post or even a number of posts to cover this broad subject, but in the meantime let’s see how easily we can generate a new XML document and parse the content of an existing one. Imagine we want to create/parse following XML document:

Creating a new XML document

In Groovy in order to the create the above XML document one needs to execute following code:

You have to admit this a WYSIWYG solution in comparison to the means offered in standard Java, where for every single node or attribute you need create a separate object and a number of helper classes as i.e. DocumentFactory. You can easily loose the big picture of the XML being created in pure Java due to the complexity of the code necessary for creating a document.

Parsing an existing XML document

Now, let’s see how easy it is to parse an existing XML document and retrieve its content. Please note that in Groovy there is no need for defining any additional classes that would represent an XML’s structure nor to create any DocumentFactory kind of objects in order to start working with an XML – just short, single line of code and we are good to go.

Operating on collections

One of features I find most useful in Groovy due to its day-to-day utilization is how it handles operations on collections. Methods like each (do something for every element), findAll (return a subset build of elements that satisfy given condition), collect (create a new collection based on elements from the old collection) presented in previous examples are only some among many.

Invoke method on every element of list

Imagine you have a list of Observer objects and on every one of them a method update should be invoked as a result of some action. You can use an asterix in order to do so.

Group elements in list by some criteria

Imagine we have a list of Jedis and Siths and now we would like to separate one from another. We can use a groupBy method that will divide our list into a map with two separate lists of characters. Every list will be saved under a key equal to the side of characters it represents.

Max/min elements

Now image we have a list of F1 drivers and we would like to get the one with the most Championships won. In order to do so we need to select the element for which the attribute championships is the highest.

Sort elements

We can also sort this list by the number of championships won by each of drivers.

Swapping values of two variables

Of course Groovy has many more cool features. The one that springs to my mind at once is a possibility of making multiple assignments. I remember that nearly every book that I read in my early adolescence about some programming language basics presented a problem of swapping values between two number variables, saying it can be only achieved by using the third, temporary variable. After all these years I am able to do this now without the additional variable, using the following syntax:

Ok, I know it’s pretty simple example, but you have to admit it makes your code more elegant. Plus it can be applied for more demanding scenarios as well. My point is, Groovy is full of such small improvements that will make your life easier.

How can I use it?

One of the greatest things in Groovy, which I believe makes it a particularly useful tool is that its scripts can be executed within Java code and vice versa. You can use groovy:

  • as a standalone script:
    • executed from the command line or using groovy shell,
    • as a part of maven processing (i.e instead of ant script),
  • in cooperation with Java:
    • compile Groovy and Java classes interacting with one another to the same jar,
    • compile Groovy scripts at the runtime and execute them from Java application.

Ok, I’m in. Where do I start?

You really don’t need much to start your adventure with Groovy. All you require to have despite Groovy is an JDK but my guess is that you already have one as a Java developer. For installation tutorial please visit Groovy’s official page under this address. This will allow you to execute Groovy scripts through the command line and Groovy Shell. In one of the following posts I will show you how to combine Groovy with Java and set up a Groovy project in the IntelliJ.

External links

2 thoughts on “What is Groovy?”

Please join discussion