Mastering Groovy
Table of Contents
Chapter 1: Introduction
Test. Let us learn Groovy. It has different use cases and learning it is probably good for your career as well :) No it will definitely be beneficial. Groovy is a programming language with Java like syntax which came into existence in 2003. To know more you can go to https://groovy-lang.org/ the official site.
Optionally type: As compared to Java you are not required to declare the variable type.
def a = 123 def b = 123.5 def c = "I am a string"
Dynamic programming language: Data type is checked at run time.
In Java you have to declare the data type before you can use it.
int i; i = 10;
Whereas in Groovy no need to declare the data type.
i = 10
Tip: Watch Introduction and what is Groovy. 1
Who this book is for?
So wondering if this book can help you or not?
- If you are like me who has programming experience already but for some reason wants to learn Groovy then this book is for you.
- You want to learn automation in Jira.
Tip: Apart from reading this book I also recommend you to take a look at the video Mastering Groovy playlist on YouTube (completely free of cost).
Getting started with Groovy
Installation
Go to www.groovy-lang.org and download or set it up on your system. It works on Windows, Linux and Mac. Since I am doing it on Mac so you can simply install Groovy using brew. I highly recommend you to read this page first to find out the distribution suitable for you.
- Prerequisites
Groovy requires Java. So install it first. Check the system requirements on the link shared above.
java -version
- Install Groovy on Mac
brew install groovy
- Install Groovy on Windows
You can download the windows installer from the download page.
- Install Groovy on Linux
There several methods but one simple way is to use SDKMAN. Instructions can be found on this page.
- Manual installation
If you are little adventurous then you can also install it manually.
- Download the zip and unpack it to a local directory.
- Set
GROOVY_HOME
envrionment variable to that directory. - Add
GROOVY_HOME/bin
to yourPATH
variable. Basically this will ensure you can rungroovysh
from any directory on your operating system. - Set your
JAVA_HOME
envrionment varible to point to you JDK.
Initial checks
If you have managed to successfully install Groovy as mentioned above then now it is time to verify your installation and check groovy version on your terminal.
groovy --version
If groovy is installed then you should get something like this on your terminal.
Groovy Version: 4.0.18 JVM: 11.0.21 Vendor: Eclipse Adoptium OS: Linux
Check for groovy shell.
groovysh --version
@ | green Groovy Shell | @ 4.0.18 |
Groovy also comes with a compiler.
groovyc --version
Groovy | compiler | version | 4.0.18 | |||
Copyright | 2003-2023 | The | Apache | Software | Foundation. | https://groovy-lang.org/ |
Tip: Watch a video on how to install Groovy and different checks. 2
Tools you need for learning Groovy
There are different tools you can use to run groovy scripts.
- Groovy web console
Yes you can try Groovy without installing anything on your computer if you have Internet connection (and a computer as well I guess).
Click here to get started.
- Groovy Console
From your terminal run Groovy Console.
groovyConsole
- IntelliJ IDE
You can install IntelliJ, it has a free community edition that works perfectly and it is all you need to learn Groovy and develop. It works on Mac, Windows and Lunux.
Using IntelliJ is very easy. Here are the steps to get started with IntelliJ.
- Launch IntelliJ.
- Create New Project.
- Select Groovy.
- Configure Project SDK and point it to your JDK installed on your computer. The location should be same as
JAVA_HOME
location. - Configure Groovy library and point it to the directory where you installed it. Check
which groovy
to know the location. On Mac the.sdkman
folder is hidden, so to find it in the Finder use a shortcut Command+Shift+dot. - Click Next.
- Enter Project name and Project location.
- On the left side there is a
src
folder. Right click on it | New | Package and enter something likein.ravisagar.masteringgroovy
. This will help in organising the code better. - Inside the package create a new Groovy Script
helloWorld.groovy
.
package in.ravisagar.masteringgroovy println "Hello World"
- Right click on
helloWorld.groovy
| Run 'helloWorld'
Hello World
Check the video. 3
Chapter 2: Groovy fundamentals
Write code for FizzBuzz game
The best way to learn a programming language is by getting your hands dirty. The more you write code solving different problems, the better you will become.
What FizzBuzz?
It is a popular game used to teach children (and adults) about division. Player take turn to count numbers from 1 to let us say 100, replacing any number divisible by 3 with Fizz, any number divisible by 5 with Buzz and any number divisible by both 3 and 5 with FizzBuzz.
The output will be like 1, 2, Fizz, 4, Buzz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, Fizzbuzz, 16, …
Simple right?
Let us write code for it.
package in.ravisagar.masteringgroovy for (int i = 1;i<=100;i++) { if (i%3==0 && i%5 ==0) {println "FizzBuzz"} else if (i%3==0) {println "Fizz"} else if (i%5 ==0) {println "Buzz"} else {println i } }
You can watch this video as well. 4
Comments
Single line comment
// Comment on a single line println "My name is Ravi" //Yes that is my name
Multi line comment
/* Comment spanning more than one line */ println "We are learning about comments"
Groovydoc comment
Starts with /**
and end with */
. Main purpose is to generate documents that will explain your classes.
/** * A Class description */
Shebang line
This is for allowing groovy code to be run from the command line on UNIX based systems. Of course groovy should be installed and in your path.
Create a file called in.ravisagar.masteringgroovy.shebang.groovy
with the following simple code.
#!/usr/bin/env groovy println "This is testing the in.ravisagar.masteringgroovy.shebang comment"
Make the file executable.
chmod a+x in.ravisagar.masteringgroovy.shebang.groovy ./in.ravisagar.masteringgroovy.shebang.groovy
Variables and Data types
A container that can store a value used in the program. Those values can be updated as needed during the execution of the program.
In the previous FizzBuzz program we used variable int i
. We were kind enough to declare data type of i
which brings us to the concept of data types
.
Variable declarations
We can tell the compiler in advanced how to use the variable. It can be declared by their type like int i
or String name
or also by using def num
or var k
.
Data types
Let me start by asking you what is the difference between 123
and India
? No prize for guessing. First one is a number but second one is a string. Now let me ask you one more question. Is 123
different from 123.5
? Both are numbers but 123.5
has a fraction.
I hope you get the idea. When you are using variables in Groovy you have the option to also define them with their data type. This make it easier for the compiler to know their purpose. Although you Groovy doesn't require you to define variable or their data types.
Write code to write file to file system and also delete a file
Let us get our hands dirty again. If you are going to use Groovy then sooner or later you will be working with files. So today let us write a simple code to write a file
package in.ravisagar.masteringgroovy import java.io.File def currentDirectory = System.getProperty("user.dir") def fileName = "testFile.txt" File file = new File(currentDirectory+"/"+fileName) file.write("This is great") file.delete()
Methods in Groovy
Let us say you have to sum two numbers. Of course no rocket science here and you can write small piece of code to do it.
def a = 1 def b = 2 c = a + b assert(3) == c
What if you want to calculate difference between two dates? Sure it is nothing too complicated and can be done with fews lines of code (or even less) but what if you have to calculate this date difference multiple times during your code execution?
That is where methods come into picture.
- You define a method and give them a task to perform (like adding two number).
- Their job is to perform that function whenever you want.
- So if you have to calculate date difference between two date you simple ask this method or call it.
- When you call that method just pass those two dates as parameters.
Let us understand this with a simple example.
package in.ravisagar.masteringgroovy def a = 1 def b = 3 def c = a + b assert(4) == c println "a + b = " + c def sumTwoNumbers(a,b) { c = a + b return c } println "a + b = " + sumTwoNumbers(a,b)
In the example above we are adding two numbers. We defined a simple method to perform this task for us.
Methods are really important not just in Groovy but in any programming language. It makes your life much easy and helps you achieve your goals with less lines of code.
Collections in Groovy
Probably one of the most important feature. Groovy has collection types - list, maps and ranges. From my personal experience I can tell you that will be using collections quite a lot.
List
- Let us define a list and do some basic operations.
def emptyList = [] assert emptyList.size() == 0 //Check size of the list def listNumber = [1,2,3,4] assert listNumber.size() == 4 assert listNumber == [1,2,3,4] assert listNumber.get(0) == 1 //Get the value at first position assert listNumber[1] == 2 //Get the value at second position assert listNumber instanceof java.util.List assert listNumber.contains(3) == true //contains() is a method to search within a list listNumber.add(5) assert listNumber == [1,2,3,4,5] listNumber.addAll([6,7]) //Add all the individual members assert listNumber == [1,2,3,4,5,6,7]
- Iterating a list
If you are learning Groovy then I can tell you that you will be doing lot of work with lists.
package in.ravisagar.masteringgroovy def listCountries = ["UK","India","USA", "France"] assert listCountries == ["UK","India","USA", "France"] listCountries.each { println "Country: $it" //it is the current element } listCountries.eachWithIndex { i, it -> //it is the current element and i is the index println "$i: $it" }