An introduction to Groovy
Posted On June 21, 2007 by Ramdas S filed under Miscellaneous
The interest in Groovy seems to be growing at a remarkable pace. Even among readers of DeveloperIQ there seems to be a demand for more information on Groovy, going by the number of mails we have received. This article presents some of the interesting features of Groovy. The idea is to demonstrate the power of this scripting language. This is not a tutorial on Groovy.
Groovy is an Open Source written in Java and integrated tightly to the Java platform. Unlike Jython, which is a Java implementation of Python, Groovy is written from scratch with only the Java platform in mind. However, the language has drawn inspiration from a number of languages, including Python and Ruby.
Getting Started
You can download the appropriate Groovy distribution from the website (http://www.groovy.codehaus.org). Alternatively, you can find the files in the July and August 2005 editions of DeveloperIQ.
Installation is not at all complicated. You need to download and unzip the files into a directory and set the GROOVY_HOME environment variable to the directory where the files are unzipped. Also, ensure that the JAVA_HOME environment variable is set to a version of JDK 1.4 or above. It is unlikely that Groovy will run on your PC if these settings are not proper.
You can find in the directory where you have unzipped the Groovy files, a subdiretory named ‘bin’ which contains all the Groovy executables. You can start working on Groovy either from the shell (using the command groovysh) or from a Java Swing Console (using the command groovyConsole).
The Groovy shell and console are different from that of Python or Perl. Unlike these languages, where each and every line is interpreted, you need to tell the Groovy interpreter to actually intrepret the script.
Open the Groovy shell using the groovysh command.
groovy> print "Hello World!"
groovy> go
Hello World!
groovy>
Presto! You just wrote your first program in Groovy. Note that you can write lines of gibberish provided some of it is not Groovy keywords, but the shell will not intrepret anything, till you give the magic command ‘go’.
You can try some simple alegbra, as given in the snippet below (code 1)
groovy> x=10
groovy> y=12
groovy> z=18
groovy> sum =x+y+z
groovy> print sum
groovy> go
40
groovy>
Remember, Groovy is a dynamically typed language. Dynamic typing even includes high level abstraction, where you can pass a method to a method, a method to a class and a class to a method and much more.
However, Groovy has certain quirkies which many developers will find it difficult to digest. You can, for example, have lines of code with semicolon (;) too. When a method is called you have options for using or not using the parameter, resulting in ambiguity at times. All Groovy methods and properties are public by default. You can swing from static to dynamic typing as you wish. The last one is a good idea and makes sense when you want to make sure that data types do not mingle. However, I dread to read through thousands of lines of code which do not adhere to clear standards.
Though Groovy is dynamically typed, it is meant to support all Java data types. Groovy even supports a range of container types like lists and maps. Python and Ruby developers will find these concepts easy to understand.
Groovy derives the string data type from Java.lang.string. Groovy uses both " and ' for strings. Either can be used. Using either type of strings allows you to utilize strings with quotations easily. When double quotes are used, they can contain embedded values. The syntax for an embedded value is ${expression} which is just like Ruby except $ is used instead of #. Let us see an example (code 2).
groovy> name = 'Bond'
groovy> age = 47
groovy> salary = 1134.34
groovy> println "My Name is ${name}, my age is ${age} and my salary is ${salary}
pounds"
groovy> go
My Name is Bond, my age is 47 and my salary is 1134.34 pounds
Loops and Branching Control Structures
Groovy has a very wide range of Control Structures. Fundamentally the if...else statement is useful in branching logic (code 3).
groovy> x=7
groovy> y=7
groovy> if (x==y) {print "They are equal"}
groovy> else
groovy> {print "They are not Equal"}
groovy> go
They are equal
Note that you branch blocks using the familiar double parenthesis in Groovy. You also have the switch statement, which works exactly like in Java.
Groovy is rich in terms of the number of options to loop. In fact, there are six different ways you can write a simple counter program in Groovy. I am not explaining the syntax but essentially each of these code snippets does exactly the same. It counts from 1 to 10. Note that each script is separated by the execution statement go (code 4).
groovy> for (i in 1..10) {println i}
groovy> go
groovy> i=1
groovy> while (i<=10) { println i; i++}
groovy> go
groovy> 10.times {println it +1}
groovy> go
groovy> (1..10).each { println it }
groovy> go
groovy> 1.step(11,1) { println it}
groovy> go
groovy> 1.upto(10) {println it}
groovy> go
Remember, in Groovy there are two types of range operators (... and …).
1..10 (allocates range from 1 to 10)
1…10 (allocates range from 1 to 9)
‘a’...‘z’ (allocates range from ‘a’ to ‘z’)
‘A’…’Z’ (allocates range from ‘A’ to ‘Y’)
Additionally, you can set the reverse range, e.g. the statement
(10...1).each {println it} prints the reverse counter. Note that ‘it’ in this case is a syntax that cannot be done without.
Functions
Functions in Groovy are described using the familiar def syntax, made popular by Python and Ruby. Here is a simple function.
groovy> def welcome(x){println "Hi ${x}"}
groovy> welcome('Bond')
groovy> go
Hi Bond
Closures
Now we come to the very important idea of closures. Closures are functions which remember their lexical environment, i.e. they have some state of their own. You can think of each closure as a little package comprising two items – a pointer to a function and a pointer to a set of name/variable bindings. Closures can typically be treated like any other programming language objects – they can be stored in variables, passed to functions, etc.
Groovy has implemented closures in a way that considerably reduces the number of lines of code you write in a program.
Let’s take an example. I want to print each word from a sentence. The sentence is stored as a string in Groovy. You can use the tokenize command and then print it. One way of doing it is as given below (code 5):
groovy> sentence = "I love My India"
groovy> y = sentence.tokenize()
groovy> for (i in y) {println i }
groovy> go
I
love
My
India
Now you could write the same program in a single line and achieve the same result.
groovy> sentence.tokenize().each {println it}
What you have just seen is a simple example. Now we will try creating the multiplication table of 7 using closures.
groovy> (1..10).each {println " ${it} * 7 = ${it*7}"}
groovy> go
The above code will print the multiplication table of 7. Writing the same program in Java will involve not less than seven lines of code! Here, we have used the range operator and printed the multiplication table.
Fundamentally, what the compiler recognizes is a chunk of code between the parenthesis and works from there, identifying the parameters needed to execute that chunk of code.
Essentially, the syntax of a closure is as follows:
Closure = {parameter-list | statements}
The parameter-list in this case is a list of parameters that are comma separated. Statements can make use of these parameters. You can execute the closure just like a function. Check out this example for calculating the simple interest (code 6).
groovy> interestEarned = {amount, rate, years | amount*rate*years}
groovy> I=interestEarned(1000, 0.08,5)
groovy> print I
groovy> go
400.00
Maps and Lists
These are again ideas borrowed from Python and Ruby. You can have lists in Groovy. I have written a simple list of integers and applied some built-in methods found in Groovy. Groovy Lists are actually instances of java.util.ArrayList.
groovy>list = [9,6,18,2]
groovy> list.sort()
groovy> print list
groovy> go
[2, 6, 9, 18]
Similarly, Lists support min and max functions:
groovy> list.sort()
groovy> print list
groovy> go
[2, 6, 9, 18]
Maps are similar to the concept of Hash Tables in C# or Directories in Python. Maps are essentially key value pairs. Unlike Python it is stored in square brackets. Here is an example.
groovy> map = ["one":1, "two":2, "three": 3]
groovy> print map["two"]
groovy> go
That is all for this month. In the next issue, we shall explore more ideas in Groovy. We will look at some of the advanced topics – Object Oriented programming, Groovy Beans and also Groovlets. Watch out for a Groovier experience!
Groovy is an Open Source written in Java and integrated tightly to the Java platform. Unlike Jython, which is a Java implementation of Python, Groovy is written from scratch with only the Java platform in mind. However, the language has drawn inspiration from a number of languages, including Python and Ruby.
Getting Started
You can download the appropriate Groovy distribution from the website (http://www.groovy.codehaus.org). Alternatively, you can find the files in the July and August 2005 editions of DeveloperIQ.
Installation is not at all complicated. You need to download and unzip the files into a directory and set the GROOVY_HOME environment variable to the directory where the files are unzipped. Also, ensure that the JAVA_HOME environment variable is set to a version of JDK 1.4 or above. It is unlikely that Groovy will run on your PC if these settings are not proper.
You can find in the directory where you have unzipped the Groovy files, a subdiretory named ‘bin’ which contains all the Groovy executables. You can start working on Groovy either from the shell (using the command groovysh) or from a Java Swing Console (using the command groovyConsole).
The Groovy shell and console are different from that of Python or Perl. Unlike these languages, where each and every line is interpreted, you need to tell the Groovy interpreter to actually intrepret the script.
Open the Groovy shell using the groovysh command.
groovy> print "Hello World!"
groovy> go
Hello World!
groovy>
Presto! You just wrote your first program in Groovy. Note that you can write lines of gibberish provided some of it is not Groovy keywords, but the shell will not intrepret anything, till you give the magic command ‘go’.
You can try some simple alegbra, as given in the snippet below (code 1)
groovy> x=10
groovy> y=12
groovy> z=18
groovy> sum =x+y+z
groovy> print sum
groovy> go
40
groovy>
Remember, Groovy is a dynamically typed language. Dynamic typing even includes high level abstraction, where you can pass a method to a method, a method to a class and a class to a method and much more.
However, Groovy has certain quirkies which many developers will find it difficult to digest. You can, for example, have lines of code with semicolon (;) too. When a method is called you have options for using or not using the parameter, resulting in ambiguity at times. All Groovy methods and properties are public by default. You can swing from static to dynamic typing as you wish. The last one is a good idea and makes sense when you want to make sure that data types do not mingle. However, I dread to read through thousands of lines of code which do not adhere to clear standards.
Though Groovy is dynamically typed, it is meant to support all Java data types. Groovy even supports a range of container types like lists and maps. Python and Ruby developers will find these concepts easy to understand.
Groovy derives the string data type from Java.lang.string. Groovy uses both " and ' for strings. Either can be used. Using either type of strings allows you to utilize strings with quotations easily. When double quotes are used, they can contain embedded values. The syntax for an embedded value is ${expression} which is just like Ruby except $ is used instead of #. Let us see an example (code 2).
groovy> name = 'Bond'
groovy> age = 47
groovy> salary = 1134.34
groovy> println "My Name is ${name}, my age is ${age} and my salary is ${salary}
pounds"
groovy> go
My Name is Bond, my age is 47 and my salary is 1134.34 pounds
Loops and Branching Control Structures
Groovy has a very wide range of Control Structures. Fundamentally the if...else statement is useful in branching logic (code 3).
groovy> x=7
groovy> y=7
groovy> if (x==y) {print "They are equal"}
groovy> else
groovy> {print "They are not Equal"}
groovy> go
They are equal
Note that you branch blocks using the familiar double parenthesis in Groovy. You also have the switch statement, which works exactly like in Java.
Groovy is rich in terms of the number of options to loop. In fact, there are six different ways you can write a simple counter program in Groovy. I am not explaining the syntax but essentially each of these code snippets does exactly the same. It counts from 1 to 10. Note that each script is separated by the execution statement go (code 4).
groovy> for (i in 1..10) {println i}
groovy> go
groovy> i=1
groovy> while (i<=10) { println i; i++}
groovy> go
groovy> 10.times {println it +1}
groovy> go
groovy> (1..10).each { println it }
groovy> go
groovy> 1.step(11,1) { println it}
groovy> go
groovy> 1.upto(10) {println it}
groovy> go
Remember, in Groovy there are two types of range operators (... and …).
1..10 (allocates range from 1 to 10)
1…10 (allocates range from 1 to 9)
‘a’...‘z’ (allocates range from ‘a’ to ‘z’)
‘A’…’Z’ (allocates range from ‘A’ to ‘Y’)
Additionally, you can set the reverse range, e.g. the statement
(10...1).each {println it} prints the reverse counter. Note that ‘it’ in this case is a syntax that cannot be done without.
Functions
Functions in Groovy are described using the familiar def syntax, made popular by Python and Ruby. Here is a simple function.
groovy> def welcome(x){println "Hi ${x}"}
groovy> welcome('Bond')
groovy> go
Hi Bond
Closures
Now we come to the very important idea of closures. Closures are functions which remember their lexical environment, i.e. they have some state of their own. You can think of each closure as a little package comprising two items – a pointer to a function and a pointer to a set of name/variable bindings. Closures can typically be treated like any other programming language objects – they can be stored in variables, passed to functions, etc.
Groovy has implemented closures in a way that considerably reduces the number of lines of code you write in a program.
Let’s take an example. I want to print each word from a sentence. The sentence is stored as a string in Groovy. You can use the tokenize command and then print it. One way of doing it is as given below (code 5):
groovy> sentence = "I love My India"
groovy> y = sentence.tokenize()
groovy> for (i in y) {println i }
groovy> go
I
love
My
India
Now you could write the same program in a single line and achieve the same result.
groovy> sentence.tokenize().each {println it}
What you have just seen is a simple example. Now we will try creating the multiplication table of 7 using closures.
groovy> (1..10).each {println " ${it} * 7 = ${it*7}"}
groovy> go
The above code will print the multiplication table of 7. Writing the same program in Java will involve not less than seven lines of code! Here, we have used the range operator and printed the multiplication table.
Fundamentally, what the compiler recognizes is a chunk of code between the parenthesis and works from there, identifying the parameters needed to execute that chunk of code.
Essentially, the syntax of a closure is as follows:
Closure = {parameter-list | statements}
The parameter-list in this case is a list of parameters that are comma separated. Statements can make use of these parameters. You can execute the closure just like a function. Check out this example for calculating the simple interest (code 6).
groovy> interestEarned = {amount, rate, years | amount*rate*years}
groovy> I=interestEarned(1000, 0.08,5)
groovy> print I
groovy> go
400.00
Maps and Lists
These are again ideas borrowed from Python and Ruby. You can have lists in Groovy. I have written a simple list of integers and applied some built-in methods found in Groovy. Groovy Lists are actually instances of java.util.ArrayList.
groovy>list = [9,6,18,2]
groovy> list.sort()
groovy> print list
groovy> go
[2, 6, 9, 18]
Similarly, Lists support min and max functions:
groovy> list.sort()
groovy> print list
groovy> go
[2, 6, 9, 18]
Maps are similar to the concept of Hash Tables in C# or Directories in Python. Maps are essentially key value pairs. Unlike Python it is stored in square brackets. Here is an example.
groovy> map = ["one":1, "two":2, "three": 3]
groovy> print map["two"]
groovy> go
That is all for this month. In the next issue, we shall explore more ideas in Groovy. We will look at some of the advanced topics – Object Oriented programming, Groovy Beans and also Groovlets. Watch out for a Groovier experience!
