Getting your Grails on: Groovy Demo

 

This is an excerpt from my upcoming book Getting your Grails on, based on my presentation from Kansas City Developers Conference.

In this chapter, we want to get your hands dirty and write and run some Groovy code through its paces. We first start setting up your computer to play with Groovy. You can download Groovy from here. Or you can use the Groovy eVironment Manage or GVM for short. The GVM tool allows you to install on any Bash platform easily. Or you can install from some of the build tools such as Gradle or Maven.

 

I will let you follow along with my install on my Windows machine.

Step 1. Download the latest version of Groovy (Currently version 2.4.4).

 

The current version is 57MB, not a huge file. I unzipped it and copied it to my C:\Java\apache-groovy-sdk-2.4.4\groovy-2.4.4 folder.

 

Step 2: Set our GROOVY_HOME

 

In my Windows machine, we need to open the Environment Variables settings.

Step 3: Add the GROOVY_HOME/bin to your PATH

Add this and click OK.

Step 4: Verify it is working by open a command prompt and typing groovy -version

 

Let’s create a simple program using Groovy. So in my home directory I created a folder called groovy and added a file called hello.groovy. The contents of the file look like this:

class HelloWorld {

  static main( args ){

     println “Hello World!”

  }

}

Then I open a command prompt and run the program with the command groovy hello.groovy.

 

Using the Groovy Console

Another great way to learn Groovy and avoid the steps of installing Groovy is to use the Groovy console that is available online. Just surf over to https://groovyconsole.appspot.com/ with any browser and you can get started.

 

Let’s start with the traditional program. Type the following into the Groovy console click on execute the script.
println “Hello world!”
Hopefully, you see something like this. It is humble beginnings, but you are off into a new world.
Variables

It is nice to print things out but you might need to assign some values into a variable or two. Try out the following lines in the Groovyconsole.
def x = 1
println x
x = new java.util.Date()
println x
x = -3.1499392
println x

Maps and collections

In Java, the collections API is a powerful tool, in Groovy in is very similar. You can do things like creating an empty list and add elements to the list.
def technologies = []
technologies.add(“Grails”)

You can use left shift to add and return the list.
technologies << “Groovy”

Perhaps you want to add multiple elements or remove an element, try this.
technologies.addAll([“Gradle”,”Griffon”])
technologies.remove(“Griffon”)

Groovy can remove items with subtraction as well.
technologies = technologies – ‘Grails’

There are a few ways you can iterate over a list of elements.
technologies.each { println “Technology: $it”}
technologies.eachWithIndex { it, i -> println “$i: $it”}

 

A few ways to check a list if it contains an element.

contained = technologies.contains( ‘Groovy’ )
contained = ‘Groovy’ in technologies
technologies.containsAll([‘Groovy’,’Grails’])

If you need to sort a list you can do that easily with Groovy, like in Java.

technologies.sort()

Manipulating Lists

There are a few ways to manipulate list in Groovy, for instance if you need to replace every occurrence of a word you can use the replaceAll().
Collections.replaceAll(technologies, ‘Gradle’, ‘gradle’)

Or if you need to shuffle a list you can do that with shuffle().
Collections.shuffle(technologies, new Random())

And to clear a list do this.
technologies.clear()

Let’s move on to maps and how can create an empty map and add some values.
def devMap = [:]
devMap = [‘name’:’Roberto’, ‘framework’:’Grails’, ‘language’:’Groovy’]
devMap.put(‘lastName’,’Perez’)

We can also iterate over elements of a map
devMap.each { println “$it.key: $it.value” }
devMap.eachWithIndex { it, i -> println “$i: $it”}

and evaluate if a map contains a key or value.
assert devMap.containsKey(‘name’)
assert devMap.containsValue(‘Roberto’)

It is easy to get the keys and values of a map too.
println devMap.keySet()
println devMap.values()

Groovy Beans

Groovy Beans are similar to Java Beans, they use a much simpler syntax. Groovy is compiled to bytecode using the following rules. If the name is declared with an access modifier (public, private or protected) then a field is generated. Names can be declared with no access modifier generates a private field with public getter and setter. When a property is declared final the private field is created final and no setter is generated.

If you want a private or protected property you have to provide your own getter and setter which must be declared private or protected. If you access a property from within the class the property is defined in at compile time with implicit or explicit this Groovy will access the field directly instead of going through accessor methods. If you access a property that does not exist using the explicit or implicit foo, then Groovy will access the property through the meta class, which may fail at runtime.

Here is a simple class to demonstrate with a read-only property name and the public getter and setter. Also, note that the lastName is a dynamically typed variable.
class Foo {
   final String name = “Roberto”
   String language
   protected void setLanguage(String language) { this.language = language }
   def lastName
}

Looping and Branching

Looping and branching in Groovy look similar to Java and other languages. Here is an example of the if else syntax.

def x = 3
if(x==1) {
   println “One”
} else if(x==2) {
   println “Two”
} else {
   println “X greater than Two”
}

As in Java, Groovy also has a for in loop to iterate over a range of values.

def x = 0
for (i in 0 .. 30) {
   x += i
}

We can also use it to iterate over a list of values.
x = 0
for( i in [5,3,2,1] ) {
   x += i
}

To loop over an array, we can use for in as well.
array = (0..20).toArray()
x = 0
for (i in array) {
   x += i
}

For in loops can also iterate over a map in Groovy too.
def map = [‘name’:’Roberto’, ‘framework’:’Grails’, ‘language’:’Groovy’]
x = 0
for ( e in map ) {
   x += e.value
}

Closures
Closures are like a “code block” or a method pointer. It is a piece of code that is defined and then executed at a later point. Closures are an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable. A closure may reference variables declared in its scope. Closure in the Groovy language can also contain free variables which are defined outside of its surrounding scope.

Here is a simple example of a closure in Groovy.
def clos = { println “Hello World!” }
println “Executing the Closure:”
clos()

To pass parameters to a closure, you can do it like this. In the second example note that you can refer to variables not listed in their parameter list.
def sum = { a, b -> println a+b }
sum(2,4)
def x = 5
def multiplyBy = { num -> num * x }
println multiplyBy(10)

Expando

The Expando class is a dynamic bean so we can add properties and we can add closures as methods to an instance of this class.

    def user = new Expando(name:”Roberto”)
     assert ‘Roberto’ == user.name

user.lastName = ‘Pérez’
     assert ‘Pérez’ == user.lastName

     user.showInfo = { out ->
             out << “Name: $name”
             out << “, Last name: $lastName”
     }
     def sw = new StringWriter()
     println user.showInfo(sw)

No comments yet.

Leave a Reply

Powered by WordPress. Designed by Woo Themes