Friday, March 27, 2009

Groovy types

Java is a statically typed language, which means we have to declare the type of a variable at compile time. Python is dynamically typed. which means that references can never to bound to types at compile time. Groovy on the other hand has optional typing. What this means is Groovy references can be statically typed like in Java, or dynamically typed like in Python.

String staticStr = new String("this is a statically typed String");
staticStr = 8;
println """The type of staticStr is: ${staticStr.class.getName()} """
println """It's value is: $staticStr"""

The output form running the above program is:

String staticStr = new String("this is a statically typed String");
staticStr = 8;
println """The type of staticStr is: ${staticStr.class.getName()} """
println """It's value is: $staticStr"""

As you can see, staticStr remains a string even after it is assigned 8. I will leave it as an exercise to figure out how 8 got assigned to a string type.

//s is not declared to be of any type but holds a String object
def dynamicStr = "this ia a dynamic string"
dynamicStr = 90
println """Type of dynamicStr is ${dynamicStr.class.getName()}"""

The output from running the above code is:

Type of dynamicStr is java.lang.Integer

So, why does Groovy support optional typing? Groovy tries to be feature rich language with support for closures and meta-programming. Both these need Groovy to be dynamically typed. However Groovy also promises compatibility with Java. Hence there are times when we may want it to be statically typed. Groovy takes the unique approach of being an optionally typed language, which allows it to be feature rich and compatible with Java.

I would like to take a little detour here and quote something I read:

"The recent trend is towards dynamically typed languages, which use inference to reduce the amount of code to be written. Java, C# and C++ are "static typed" languages, whereas JavaScript, Ruby, Python and PHP (used by Facebook) use "dynamic typing". In static languages, the programmer must declare each variable's class (such as string, integer, or list) before the program runs; in dynamic typing, it is assessed as the program runs. Fowler says Ruby is between two and five times more productive than Java. "In static languages, there are all these speed bumps. You can just express yourself more rapidly in languages like Ruby and Python, and that gives you an edge. That edge does make a significant productivity difference." - Source: The Guardian

I will not discuss details of static vs. dynamic typing in this blog post, but suffice to say that dynamic typing makes it possible for Groovy to have flexible closures, and metaprogramming. Groovy supports static types to allow inter operation with Java. This is very nice, because not only can a Groovy program take advantage of existing Java libraries, but Java programmers who are not yet fully familiar with Groovy can start Groovy programming with a known paradigm and proceed with closures and metaprogramming as their knowledge of Groovy increases.

Wednesday, March 25, 2009

Groovy Ranges

Groovy Collections offer us a class in addition to Java Collections, called Range. Range is a subclass of java.util.List and is used for creating lists of sequential values. Some ranges can be:
Notice that we use the .. operator to create a range.

However ranges are not limited to numbers and characters. Any object which implements the methods compareTo(), next(), and previous() can be used in a Range.

Ranges typically have a left and right border, and they can be either inclusive (containing border elements) or exclusive (sans the right border element).

Ranges are usually used to extract a subset of elements from a list or used in switch statements to match a range of cases together.

The code below is self explanatory:

//A simple Groovy Range
def inclusiveRange = 1..10
println 'The size of inclusiveRange is: ' + inclusiveRange.size()

//This range does not include the right border element
def exclusiveRange = 1..<10 exclusiverange1 =" 1<..10" negativepositiverange =" -5..5" negativedescrange =" -1..-10" negativeascrange =" -10..-1" out =" new" out =" new" out =" new" out =" new" out =" new" list =" [0,1,2,3,4,5,6,7,8,9]"> 0}

Output from running the above program:

The size of inclusiveRange is: 10
inclusiveRange: 1,2,3,4,5,6,7,8,9,10,
exclusiveRange: 1,2,3,4,5,6,7,8,9,
negativePositiveRange: -5,-4,-3,-2,-1,0,1,2,3,4,5,
negativeDescRange: -1,-2,-3,-4,-5,-6,-7,-8,-9,-10,
negativeAscRange: -10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
sublist of first 4 element from list: [0, 1, 2, 3]
sublist of last 2 element from list: [9, 8]
negativeAscRange,grep(-5..-3): [-5, -4, -3]
matching all positive values in negativePositiveRange: [1, 2, 3, 4, 5]

Thursday, March 19, 2009

Groovy closures

Java does not have closures, but till sometime back it was a highly debated topic on various Java forums. Groovy is a language which compiles to Java bytecode and does have closures.

Closures are very prominent in many programming languages, such as Groovy, Python, Ruby, Javascript, and probably many more.

So what are closures? A closure is a block of code which can be passed to a function. Closures in Groovy are normal objects, which do not have any visible state.

Closures are most often used in iteration logic and resource handling.

Whenever we iterate across a collection, we normally do so to perform some logic on all or some members of the collection. Closures make it easy to represent that logic in a very concise and readable way.

Closures can also be used for resource handling. Very often we open a file resource do something with the file (read from it, write to it, or both), and then close the file. The first and last parts, that is opening and closing the file are really plumbing code. The interesting part is what we do with it. Using closures it is possible to create objects which will take care of the plumbing and will perform some operations on the file, such that the code which represents the operations are given to it in a closure.

Here is an example. Let's assume we have a list of Toy objects, where each toy object has a color which can be accessed with the getColor() method. I want all the blue toys and my sister wants all the pink toys.

Here is code to get toys for me using regular Java syntax:

Color myFavColor = Color.BLUE;
List toysIWant = new ArrayList()
Iterator iter = toys.iterator();
while(iter.hasNext()) {
Toy toy = (Toy);
if(toy.getColor().equals(myFavColor)) {

Here is code to get toys for my sister using closures:

def mySistersFavColor = Color.PINK
def toysMySisterWants = toys.grep() {
it.getColor() == mySistersFavColor

What really happened in the second code snippet was, the list object has a grep method which takes a closure. It calls that closure for every item in the list and passes that item to the closure as the variable 'it'. If the expression in the closure evaluates to true, then the item is added to an internal list. This list is returned to the caller when grep returns.

You might be thinking that this can be done in Java using anonymous inner classes. That is partially right. But there are two very important differences. Anonymous inner classes cannot refer to non static local variables in the scope they are declared in, which means they could not have referred to the variables 'myFavCOlor', and 'mySistersFavColor'. Another difference is that anonymous inner classes are very verbose. This may not seem important, but many people have said that it is something that makes anonymous inner classes unusable.



iAccelerator is an initiative by The Centre for Innovation Incubation and Entrepreneurship at IIM Ahmedabad.

It is a startup assistance program for first time technology entrepreneurs in India. Accepted applicants will receive upto 5 Lacs in funding. Selected applicants will be expected to stay for 4 months in Ahmedabad to work on their startup. Here they will also receive help in various other aspects (legal, management, technical) of building and running their startup.

The last date for applications is April 1st.

Tuesday, March 17, 2009

Groovy Lists

In a previous post I talked about Groovy numbers. In this post we discuss Lists in Groovy. One thing that strikes me is the use of operators in Groovy. Groovy has reduced verbosity wherever possible with the use of operators.

We create a List in Java like this:
List list = new ArrayList();

and in Groovy like this:
def list = []

Why do you think we do not use generics in Groovy? You can reply on Twitter.

Groovy allows us to apply several operators like +, -, *, and <<

//Lets create an empty list. Notice, we can create a list with the []
def aList = []
//size is also an attribute in Lists (we cannot invoke methods
//without the ())
println 'size if aList is: ' + aList.size
println 'Lists created with the [] operator are of type: ' +

//What if I want a linked list?
def lList = [] as LinkedList
println 'lList is of type: ' + lList.class.getName()

//We can also create a LinkedList by specifically instantiating it
//like in Java
def aLinkedList = new LinkedList()
println 'We just created a list of type: ' +

//Now we are really pushing it
def wtfList = [] as String
println 'wtfList is of type: ' + wtfList.class.getName()

//We can add elements to a list using the << operator
aList << 'element 1' << new Date()
aLinkedList << 1

//We can also add elements to a List with push() and add()
println aList
println aLinkedList

//We can instantiate and populate a List together
def aList1 = ['a', 1, new Date(), null]
println aList1
println 'size of aList1 is: ' + aList1.size()

//We can remove elements from a List with the pop() method
println 'Removing elements from aList1 using the pop() method'
println aList1.pop()
println aList1.pop()
println 'after 2 pops the size of aList1 is: ' + aList1.size()

//Lists support negative indexes where -1 is the last element
//Notice how we have accessed a List element with the [] operator
println 'aList[-1] = ' + aList[-1]
println 'aList[0] = ' + aList[0]

//Sublists can be accesed by giving a range in the subscript
println 'aList[-1..-3] = ' + aList[-1..-3]
println 'aList[-1,-3] = ' + aList[-1,-3]
println 'aList[0..3] = ' + aList[0..3]

//empty list and Groovy truth
def emptyList = []
println 'Groovy truth for empty List is: ' +
(emptyList ? true : false)
println 'Groovy truth for non empty list is: ' +
(aList ? true : false)

def unsortedList = [3, 4, 2, 8, 5, 7]
println unsortedList
println 'sorting...'
println unsortedList.sort()
//The sort() method also takes a closure
unsortedList = [3, 4, 2, 8, 5, 7, 10, 19, 67, 3]
println 'sorting with a closure'
unsortedList.sort {it1, it2 ->
println """${it1} <=> ${it2} """;
it1 <=> it2}

//Let's understand the <=> spaceship (compareto) operator
println 'Let us understand the <=> operator'
println '1 compareto 1 = ' + (1 <=> 1)
println '1 compareto 2 = ' + (1 <=> 2)
println '2 compareto 1 = ' + (2 <=> 1)

//we can sum lists
println "SUM(unsortedList) = " + unsortedList.sum()

//can we sum lists which have non number members?
unsortedList << "string"
println "SUM(unsortedList) = " + unsortedList.sum()

//OK now let's remove the 'string' from this list
unsortedList -= 'string'
println "unsortedList after removing 'string': " +

//we can also multiply lists
def listOfGames = ['football', 'cricket', 'tennis']
println listOfGames * 2

//We can also append to a list
println "Appending lists with the << operator: " +
[1,2,3] << [4,5]

//iterating lists
println "iterating a list with the each method"
print it + " "

Output from running this code:

size if aList is: 0
Lists created with the [] operator are of type: java.util.ArrayList
lList is of type: java.util.LinkedList
We just created a list of type: java.util.LinkedList
wtfList is of type: java.lang.String
["element 1", Tue Mar 17 22:13:14 IST 2009, 2, "hello"]
["a", 1, Tue Mar 17 22:13:14 IST 2009, null]
size of aList1 is: 4
Removing elements from aList1 using the pop() method
Tue Mar 17 22:13:14 IST 2009
after 2 pops the size of aList1 is: 2
aList[-1] = hello
aList[0] = element 1
aList[-1..-3] = ["hello", 2, Tue Mar 17 22:13:14 IST 2009]
aList[-1,-3] = ["hello", Tue Mar 17 22:13:14 IST 2009]
aList[0..3] = ["element 1", Tue Mar 17 22:13:14 IST 2009, 2, "hello"]
Groovy truth for empty List is: false
Groovy truth for non empty list is: true
[3, 4, 2, 8, 5, 7]
[2, 3, 4, 5, 7, 8]
sorting with a closure
3 <=> 4
4 <=> 2
3 <=> 2
4 <=> 8
8 <=> 5
4 <=> 5
7 <=> 10
10 <=> 19
19 <=> 67
67 <=> 3
19 <=> 3
10 <=> 3
7 <=> 3
8 <=> 3
2 <=> 3
3 <=> 3
4 <=> 3
4 <=> 7
5 <=> 7
8 <=> 7
8 <=> 10
Let us understand the <=> operator
1 compareto 1 = 0
1 compareto 2 = -1
2 compareto 1 = 1
SUM(unsortedList) = 128
SUM(unsortedList) = 128string
unsortedList after removing 'string': [2, 3, 3, 4, 5, 7, 8, 10, 19, 67]
["football", "cricket", "tennis", "football", "cricket", "tennis"]
Appending lists with the << operator: [1, 2, 3][4, 5]
iterating a list with the each method
2 3 3 4 5 7 8 10 19 67

Saturday, March 14, 2009

Groovy numbers

I was very pleasantly surprised when I learned how to work with numbers in Groovy. The first difference between Groovy and Java (while dealing with numbers) is that in Groovy numbers are always objects. There are no primitive numbers like in Java. This may have the disadvantage of increased memory usage, but it also has the advantage that working with large numbers is much easier.

If you have tried doing high precision calculations or working with really large numbers in Java, then you know how difficult it is to work with BigDecimal and BigInteger to perform calculations. We have to call methods instead of using operators. Let's see this with a small example. If I want to print the value of Long.MAX_VALUE * 2, I have to use BigInteger and then invoke it's multiply method as shown in the example below:

System.out.println(Long.MAX_VALUE * 2); //Incorrect: prints -2
//The right way to work with large numbers in Java
BigInteger bi1 = new BigInteger("9223372036854775807");
BigInteger bi2 = new BigInteger("2");
BigInteger bi3 = bi1.multiply(bi2);

Output of this program is:


See how cumbersome it is to do even simple operations with integers larger than 263-1. However in Groovy, multiplying Long.MAX_VALUE with 2 would have automatically resulted in a BigInteger. Floating point numbers in Groovy are always BigDecimals, and as a rule, when we do arithmetic operations in Groovy, the result is always what we expect it to be.

This small snippet of Groovy code is self explanatory.

//It is very natural to do high precision calculations in Groovy because
//in Groovy numbers can be directly represented with BigDecimal and BigInteger
//and we can use regular arithmatic operators with them

//Numbers in Groovy are first class objects
def i = 5
println '5 is of type ' + i.getClass().getName()

def d = 5.4
println '5.4 is of type ' + d.getClass().getName()

//It is possible to explicitly create Long, Float, Double, and G???
def l = 8999000000000L
println '8999000000000L is of type ' + l.getClass().getName()

def f = 1.2F
println '1.2F is of type ' + f.getClass().getName()

def doubleObj = 1.2D
println '1.2D is of type ' + doubleObj.class.getName()

def g = 3G
def g1 = 3.5G
println '3G is of type ' + g.getClass().getName()
println '3.5G is of type ' + g1.getClass().getName()

//type conversions in arithmatic operations
//Mostly the result is what you would expect
println 'Adding Integers results in a : ' + (3 + 3).class.getName()
println 'Multiplying Integers results in a : ' + (3*3).class.getName()
println 'subtraction between Integers results in a : ' + (3-8).class.getName()
println 'Division of an Integer with an Integer results in a : ' + (3/3).class.getName()

//Integer division can be forced with the intdiv() method
def fi = 1.intdiv(2)
println 'fi is of type: ' + fi.class.getName() + ' and it\'s value is ' + fi

//Some numbers also have methods which can be used instead of for loops
//by accepting a closure
def n = 5
n.times { print """${it} """} //notice the use of GStrings

//other methods on numbers include upto, downto, and step
//we also need a more advanced example on numbers to explore all the other
//methods present in various number classes

Output of this program is:

5 is of type java.lang.Integer
5.4 is of type java.math.BigDecimal
8999000000000L is of type java.lang.Long
1.2F is of type java.lang.Float
1.2D is of type java.lang.Double
3G is of type java.math.BigInteger
3.5G is of type java.math.BigDecimal
Adding Integers results in a : java.lang.Integer
Multiplying Integers results in a : java.lang.Integer
subtraction between Integers results in a : java.lang.Integer
Division of an Integer with an Integer results in a : java.math.BigDecimal
fi is of type: java.lang.Integer and it's value is 0
0 1 2 3 4

Sunday, March 08, 2009

String handling in Groovy

This blog post shows through a simple example, how to manage strings in Groovy. Here are a few things which are different in Groovy strings:
  • Groovy strings can be enclosed within

    • single quotes: 'this is a string'

    • double quotes: "this is a string"

    • triple (single or double) quotes: '''this is a string''' and """so is this"""

  • Groovy has something called GStrings which uses replacement variables
  • Groovy makes it easier to use strings in regular expressions

  • The == operator in Groovy actually invokes the equals() method

  • Groovy overloads the +, -, and * operators in Strings

With these concepts in mind the example below should be self explanatory. Try running this example yourself and see the output. After that change the source and see how it affects the output.

//Groovy allows single quoted strings
def string1 = 'hello world'
println string1

//Groovy allows double quoted strings (GStrings have to be double quoted)
def string2 = "Hello World"
println string2

//Groovy has something called GStrings which are regular strings which can
//contain replacement variables. These can be variables, or expressions.
//GStrings have to be double quoted
def gstring = "${string2} is so outdated now!"
println gstring

//GStrings can contain expressions and they are a separate datatype in Java
println "2 + 2 = ${2+2}"
println "GString is a separate datatype in Groovy: ${gstring.class.getName()}"

//multiline strings should be enclosed within triple (single or double) quotes
//Notice how the newline character and leading spaces in lines 2 and 3 are taken
//as part of the string
def multilineString1 = """This is a really long multiline String.
In Java we would have to break up such
String into multiple Strings"""

def multilineString2 = '''This is a really long multiline String.
In Java we would have to break up such
String into multiple Strings'''

println multilineString1
println multilineString2

//In Groovy Strings can also be enclosed within / /, These are used in regular
//expressions because the backslash character does not need to be escaped in
//such Strings
def slashyString1 = / This String does not need to escape the \ character. /
def slashyString2 = / Even \n does not represent a newline /
println slashyString1 + ' ' + slashyString2

//Use == for String comparisons. Also note that double quoted Strings can
//contain single quotes
println "Is '${string1}' == '${string2}' : " + (string1 == string2)

//Groovy supports operator overloading
println 'Hello ' + "World"

//* repeats the String n times
println 'Hello ' * 3 + 'World'

//- removes the specifies substring starting from the left
println string1 - 'world'
println string1 - 'hello'
def stringOps = 'hello ' * 3 + ' world'
println stringOps - 'hello'

//Thankfully the divide operator is not supported with Strings
//println stringOps / 'hello'

//String can be directlt tokenized. We get a List type as the return
def list = multilineString1.tokenize("\n")

//Even though we will learn about ranges and lists later, here is a small
//example which shows how we can treat Strings like ranges and lists

//A String can also be accessed like a list with the [] operator
println string1[0]

//Strings can also be treated as ranges
println string1[1..5]

//ranges can also accept negative values
println string1[-5..-1]

//Strings can be centered for printing
println "'" + + "'"

//The String class overrides the << string3 =" string1">