Friday, February 27, 2009

Learning Groovy

I have started learning the Groovy programming language. Looks like dynamic languages are getting really popular these days, and keeping up with my resolution to learn a couple of programming languages this year, I have started learning Groovy.

In short Groovy is a dynamic language which fully interacts with Java. Groovy can invoke Java objects, in fact it itself compiles to bytecode, so Java objects can also invoke Groovy.

In the next few posts I will share what I learn and my notes comparing Groovy with Java.

Let's start with a HelloWorld in Groovy


println 'Hello World'


That's it. You do not need to enclose your HelloWorld in a class or the main method. This is really cool if you just want to create a simple script file to do something quickly for you.

But how does this get compiled to Java bytecode. Java always needs a class and methods to hold code. Well in my case the Groovy plugin in Eclipse automatically compiled the above code and put it in a class with the same name as the name of the file containing this code.

In this example you will also notice that:
  • Groovy Strings can be enclosed in single quotes
  • If a method takes only one parameter, we can give it to the method without enclosing the parameter in ()
  • Groovy statements do not need to be terminated with a ;

No comments: