You might be coming from a Java background and heard of Groovy “the Java scripting language”. Or you might have started with Grails to develop web applications fast and want to understand more of the Groovy syntax to fully utilize Grails’ potential. Your project might be using Gradle to configure the build process and you have looked at the code writing in Groovy and want to no more. To use Grails or Gradle, or to even write Groovy code in your Java project it is good to know the syntax and to learn what can be achieved with Groovy.
In this university session we will look at the Groovy basics and see what it is all about. We learn a bit about the background of Groovy and see quickly the differences between Java and Groovy. We don’t want to emphasize too much on theory, so we use small workshop during the session so we can get the Groovy feel ourselves and experience the true power.
We look at Groovy syntax (compare it to Java), see the different types of Groovy like several ways to express String types. We look at Groovy specific control structures and how we can use operators (and even implement our own operator implementations).
Then it is time to look at closures. Closures are a long debated subject in Java, but Groovy already supports closures, so let’s see how we can write a closure and use it.
Groovy makes working with collections very easy compared to Java. A lot of useful methods are added to collection classes and we learn more about these methods with small demonstrations.
Reading or writing contents from and to a file is very easy in Groovy as we will see. Also we see how easy it is in Groovy to read and write XML content.
Groovy supports AST code generation, this means we can add extra code to a compiled class during the compilation phase. In the Groovy library we have already very useful AST annotations to make our coding easier, because with a simple annotation we add a lot of functionality to a class.
Finally we look at a very “magical” part of Groovy: the metaprogramming capabilities. This means we can extend classes with extra functionality at runtime and it is a very powerful mechanism.