Home » JVM Languages » Groovy » Groovy Script 101 – Commonly Used Syntax Reference Guide

About Aphinya Dechalert

Aphinya Dechalert
I code. I write. I hustle. Living the #devLife remotely. Full-stack MVP developer. Coding and writing about code.

Groovy Script 101 – Commonly Used Syntax Reference Guide

Groovy has been around on the Java scene since 2003. With over a decade’s worth of history, development and experience, it is a Java syntax compatible object oriented programming language that compiles into JVM bytecode.

In a way, Groovy can be viewed as a flavor of Java without being actual Java. This is because it works on the Java platform in a native capacity. Because of the way it works, it interoperates nicely with Java code and its associated libraries. Most valid Java code also translates to valid Groovy code.

Groovy is designed to be both a programming and scripting language. This means that unlike Java, which needs to be compiled, Groovy can be used in conjunction to provide on the spot programmatic processes that doesn’t require a lot of server side heavy-lifting.

The biggest difference between Groovy and Java code is that Groovy is more compact, with less syntax requirements and therefore making it appealing to many developers. It also means that many Java developers going into Groovy will find the process of picking it up super simple. Why? Because fundamentally, most object-oriented based programming languages tend to follow the same ideas. This shared ideology makes it easy for developers to jump between Java and Groovy.

This piece will go over how to do 7 most common things that we encounter when writing code. They are the foundation and general building blocks of any program and often crop up in some form within an object-oriented based thinking.

1. Installing Groovy

You can install Groovy via your package manager. Alternatively, you can install groovy from their website.

Groovy files are saved with .groovy extension.

To execute files in the command line, you can do so using groovy. For example:

 groovy index.groovy

To run Groovy Shell, you groovysh in the command line.

2. List and maps

A list is also commonly known as an array. It stores objects sequentially and can be accessed via integer indices. In Groovy, a list looks something like this:

def shoppingList = ["flour", "eggs", "banana", "bread"]
 ​
 println shopingList[2]
 //will give "banana"
 ​
 shoppingList.remove("flour")
 shoppingList.add("milk")
 ​
 println shoppingList[2]
 //will give bread

A map holds a key-pair value based list where you can attach data to a custom named key. Rather than calling values based on integer based keys, this lets you use the custom named key instead.

def productDetails = [
  "name": "banana",
  "type": "fruit",
  "price": 2.99,
  "unit": "kg",
  "color": "yellow"
 ]
 ​
 println productDetails["name"];
 ​
 productDetails["price"] = 5.99

We can also add lists into maps like this:

def toDoList = [
  "monday": ["water plants", "laundry"],
  "tuesday": ["assignment due", "feed cat"]
 ]
 ​
 toDoList['wednesday'] = ["clean kitchen", "get groceries"]
 ​
 println toDoList['wenesday'][1]

3. Conditionals

The most basic conditionals are if else statements. The result is a boolean that determines which block of code to execute next. An if else statement in Groovy looks like this:

def myString = "I am allergic to cats."
 ​
 if(myString.contains("allergic")){
    println myString
 } else {
    println "all clear!"
 }

You can also do the expressions that evaluates to a boolean within the if statement. For example:

def myString = "I am allergic to cats."
 ​
 if(myString.contains("allergic") && myString.contains("cats")){
    println myString
 } else {
    println "all clear!"
 }

&& and || operators are conditionals known as ‘and’ and ‘or’. The statement needs to evaluate to true in order to proceed, or it goes down to the else block.

Another condition you can use to give your if else statement options beyond just the two is to use the else if option.

For example:

def myString = "I am allergic to cats."
 ​
 if(myString.contains("allergic") && myString.contains("cats")){
    println "ahchooo! blasted cats!"
 } else if(myString.contains("allergic") && myString.contains("dogs")){
    println "oh no! not dogs!"
 } else{
    println "all clear!"
 }

4. Loops

A loop is a set of code that we want to repeat under certain circumstances. Three common types of loops are: while, collection iteration, and recursion.

Let’s begin with the first of the three: the while loop.

A while loop runs through a set of execution statements until the condition is satisfied. It accepts an argument to determine the validity of the boolean evaluation.

Writing a while loop in Groovy looks something like this:

def counter = 0;
 ​
 while(counter < 10){
  counter = counter +1
  println "just counting..." + counter
 }
 ​
 println "all done!"

A collection iteration is when you work through a list, iterating it until the list is exhausted. To do this, you use the each method like this:

def children = ["James", "Albus", "Lily"];
 ​
 println "The children's names are:"
 children.each { child ->
    println child
 }

You can also iterate through maps like this:

def families = [
  "Potter": ["James", "Albus", "Lily"],
  "Weasley": ["Rose", "Hugo"],
  "Lupin": ["Edward"]
 ]
 ​
 families.each{ family, child ->
  println "The children of the " + family + " family are " + children.join(', ')
 }

And finally, we have recursions. A recursion is a function that calls itself when the conditions are met. For example, here is a function that calls itself.

def fibonnaci(n) {
  if(n <= 2) {
    return 1
  } else {
    return fibonnaci(n - 1) + fibonnaci(n - 2)
  }
 }
 ​
 println fibonnaci(4)
 println fibonnaci(5)

5. Writing JSON

You can write lists and do things to it. But what we really want is to turn this data into something more universally accessible – that is, make it into valid JSON.

Groovy includes simple classes for writing to JSON. All you have to do is import JsonBuilder and use on the list map you want to transform.

import groovy.json.JsonBuilder
 ​
 def families = [
  "Potter": ["James", "Albus", "Lily"],
  "Weasley": ["Rose", "Hugo"],
  "Lupin": ["Edward"]
 ]
 ​
 new File('familyMembers.json') << new JsonBuilder(families).toPrettyString()

The new File() will create a new file object that we assign our transformed families JSON to.

6. Reading JSON

JSON is the most popular method of moving structured data between different applications and networks. Let’s pretend we get given a JSON file containing all a giant list of inventory information.

import groovy.json.\*
 ​
 def inventoryListFile = new File('products.json')
 def inventory = new JsonSlurper().parseText(inventoryListFile.text)
 ​
 println inventory['banana']

The JsonSlurper lets you create a new instance and parseText method allows you to pass texts into your file, allowing you to modify and do what you want with the data set.

7. HTTP requests

An isolated application that doesn’t communicate with anything isn’t much use in this day and age. there’s a lot of data that gets transferred over the Internet and to do this, we need the ability to create HTTP requests.

Here’s a scaffold of how you’d write it.

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )
 ​
 import groovyx.net.http.HTTPBuilder
 import groovy.json.JsonBuilder
 ​
 new HTTPBuilder('https://en.wikipedia.org/w/api.php').get(
   'query': [
     'action': 'opensearch',
     'search': 'Harry Potter'
  ]
 ) { resp, json ->
   if(resp.status == 200) {
     def responseFile = new File('potter.json')
     responseFile.text =  new JsonBuilder(json).toPrettyString()
  } else {
     println 'Uh oh. Something went wrong:('
  }
 }

Final thoughts

I hope you found this reference helpful. It’s a quick cheat sheet style list of commonly used things you’d find in programming, but in a Groovy flavor.

If you’re coming from a Java background, everything should feel almost at home. If you’re coming from a JavaScript environment, the elements of Groovy are generally identifiable.

The fundamentals of programming are still the same, no matter where you go. Most of the time, once you learn one language, the ideas are transferable and all you have to do is learn the syntax.

From what you can see above, the ideas are mostly the same. So in theory, you can potentially close your eyes and pretend it’s Java or JavaScript but with a few differences in syntax and how certain things are run.

But for the scope of this piece, the content presented here should be enough to get you started on your next Groovy based project.

Published on Java Code Geeks with permission by Aphinya Dechalert, partner at our JCG program. See the original article here: Groovy Script 101 – Commonly Used Syntax Reference Guide

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments