Friday, May 15, 2009

Groovy & Java

Closure(s) Groovy Closures, loosely speaking are method pointers. Also, Groovy is a 2nd standard language for JVM. So, does it mean we have function pointers in Java / JVM ? No, if you read about Closures carefully enough, they are actually objects. Let’s see if we can do something close to what Groovy can do in Java.

Below is a sample code written in Groovy script


def list = []
for (i in 1..5)
list.add(i);
/*I am treating doThis as a Closure, I could have written 'Closure doThis' as well */
def doSomething(toMe, doThis){
toMe.each(doThis)
}

doSomething(list, {print it + " "})
print("\n")
doSomething(list, {print it * 5 + " "})
print("\n")
list.each{print it + " "}

Below are the results

1 2 3 4 5
5 10 15 20 25
1 2 3 4 5


In the above example, "doThis" can be anything (its loosly typed, feature of dynamic language) but I am using it as a Closure. Method named "doSomething" simply applies the "doThis" closure to "toMe" variable. yea, I know its painful when on one side you say "Following generics, it’s good for you and your code's health" and on the other side "Look @ the really cool features of Groovy, you don’t even need to declare Type".. WTF. Anyways, the point is, what will it take to do the same thing in Java, Groovy style.

Lets first declare something like closure :)


Also, lets implement our own version of List (just to include groovy stype "each" method)



Now, let’s see our code in Action


Below are the results: as expected

1 2 3 4 5
5 10 15 20 25
10 20 30 40 50
1 2 3 4 5


Then only thing interesting in MyGroovy class is below code:


In Groovy list.each() method takes a closure, which is internally just an Object. So, in our implementation of List, we are also passing instance of Closure :). BTW, I do not know how Groovy implements this concept, but this technique is a good candidate. Also, given that SpringSource owns Groovy & Grails, we might see Groovy getting even more popular for web application development. According to me, it is going to be maintenance nightmare if that happens.

No comments: