Jul 272013
 

Grails is a powerful framework that makes most programming tasks short and simple. A key ingredient to achieving this is the powerful and cool language called Groovy. Before diving into learning Grails, it is worthwhile to learn basic Groovy coding tricks.

The sample code below may seem simple. But when you use them in actual projects, you will be surprised on how much time and lines of codes you can save.

About Groovy

  • It is a superset of Java. This means any valid Java code is a valid Groovy code also. If you don’t like using Groovy, you can use plain Java syntax when working with Grails.
  • It is a dynamic language similar to Python, Ruby and Perl. This means that it supports many cool syntax and features that makes working with Groovy so much nicer than working with plain Java.
  • It is compiled to Java bytecode. This means you can run Groovy programs in any Java Virtual Machine. Similarly, Grails projects that are written in Groovy, can be deployed to Java application servers such as Tomcat, JBoss, GlassFish, and others.

Creating a Groovy Project

To play with Groovy, we need to have a Groovy project to work with. If you have not yet configured your computer for Grails development, you can follow this guide.

Start your Groovy/Grails Tool Suite IDE and create a project:
a01

Select to create a Groovy Project:
a02

Give it a project name. For example: test:
a03

Now create a Groovy class:
a04

Specify your desired class name. For example TestProgram:
a05

And it will generate a file like this:
a06

Hello World

Create this program:

package test
class TestProgram {
	static void main(args){
		println "Hello World"
	}
}

And run it:
a07

It will display the output:
a08

Weak Typing

An important thing to note in Groovy is that it is not a strong typed language. The following are valid:

static void main(args){
	def a = 'John Doe'
	a = new Object()
	a = 10
	println a
}

And will print 10 to the console.

String

Note this example:

static void main(args){
	def firstName = 'John'
	def lastName = 'Doe'
	def a = 3
	def b = 7

	println "${lastName}, ${firstName}"
	println "a + b = ${a + b}"
	println '${lastName}, ${firstName}'
	println 'a + b = ${a + b}'
}

Check the lines that invokes println. Strings that are in single quote are normal strings just like in Java. But those that are in double quotes are strings that are on steroids. The output of this will be:

Doe, John
a + b = 10
${lastName}, ${firstName}
a + b = ${a + b}

As you can see, when using the special string in double quotes, the expression inside ${} are evaluated. This makes for short, concise and clean code.

List

Data manipulation, such as list and map processing, tends to be tedious when working with Java. This is where the Groovy language shines. Check the difference of declaring a list between Java and Groovy:

List javaList = new ArrayList()		// Java
def groovyList = []			// Groovy

Both are instance of java.util.List

Initializing is simple

def alist = [5, 1, 3, 5]

And contents are not strongly typed

def myList = [10, "John", new Integer(5), new Double(7.6d)]

Appending items is like this:

def alist = [10, 9, 8]
alist << 7
alist << 6

printing the contents will result to output: [10, 9, 8, 7, 6]

Individual items can be accessed by index

def alist = ["Apple", "Banana", "Carrot"]
println alist[1]

Prints Banana.

You can get number of elements using the size() method:

def alist = ["Apple", "Banana", "Carrot"]
println alist.size()

Outputs 3

You can get a subset of a list given a criteria:

def alist = [10,11,12,13,14,15,16,17,18,19,20]
println alist.findAll{it % 2 == 0}

The above will find all elements of the list that satisfies the condition it % 2 == 0 (meaning even numbers.). The output will be: [10, 12, 14, 16, 18, 20]

You can create a new list by using each item in a list to evaluate an expression:

def alist = [1,2,3,4,5]
println alist.collect{it * 10}

Output will be: [10, 20, 30, 40, 50]

Or you can create a new list by invoking a function on each items:

def alist = ["Apple", "Basketball", "Championship"]
println alist*.length()

This creates a new list by getting the length() of each item. The output is: [5, 10, 12]

Maps


Map stores a list of key value pairs. For example:

def emptyMap = [:]		
def mapWithValues = [fruit:'Apple',  veggie:'Carrot']

The only difference between an empty map and list is the extra colon.

It is also an instance of java.util.Map and all keys are Strings by default. Here are sample ways to add and get items from maps:

def alist = [fruit:'Apple', 'veggie':'Carrot']
alist['car'] = 'Sedan'
alist.put('book', 'Novels')
alist << [pet:'Dog']
println alist['fruit']
println alist.'veggie'
println alist.get('car')
println alist.get('book')
println alist.get('pet')

Notice that fruit, even without quotes was treated as String. Map operations such as put and get are also supported.

Loops

Here are example of simple but commonly used loops.

To execute something multiple times:

5.times {
	println "Hello"
}

This will print Hello 5 times.

Looping through items of a list

['cat', 'dog', 'hamster'].each { name ->
	println name	
}

Will output: cat dog hamster

Replace for loop with a number range and looping with each item:

(6..10).each { number ->
	println number
}

Will output the numbers from 6 to 10

Looping through a map

[fruit:'Apple', veggie:'Carrot', car:'Sedan'].each { key, value ->
	println "${key} = ${value}"
}

Will output

fruit = Apple
veggie = Carrot
car = Sedan

Remarks

We can do so much more with Strings, List, Maps and Loops in Groovy. The above are just few examples to trigger interest and appreciation of the language.


List of Tutorials for Beginners

Comments

comments