Friday, December 25, 2009

Java to Groovy Incompatibilities

I'm fairly new to Groovy. One of the things which I've heard many times (from various sources) is that I can take a Java file, rename it as .groovy and can run it. While this is true for the most part, there are some incompatibilities, which caught me by surprise. The following list may not be exhaustive, but I'm listing the incompatibilities which I've read from books/online sources or came across while coding:
  1. If your Java code uses == (reference equal), then groovy does not treat it the same. In groovy == is (almost) equivalent to using .equals() method. Even this also first uses the compare() method (if present) and if that is not present, then it uses equals() method in the class to find out if the two objects are equal. If you want to compare the references of two objects, then you need to use is() in Groovy. For example, obj1.is(obj2) will return true if the obj1 and obj2 point to the same reference.
  2. def and in are keywords in Groovy. So, if your Java code has these variable names, then you may encounter issues. Also, it has a special meaning (closure parameter) in Groovy. If you have a variable named it, you might have issues.
  3. Code blocks like this are not supported by Groovy. It gets confused since it looks like a closure. { System.out.println("Code Block") }
  4. Declaring an array like int[] arr = new int[] { 10, 20, 30 } does not work in Groovy. In Groovy, it needs to be declared like int[] arr = [10, 20, 30]
  5. In Java, both public static void main(String args[]) and public static void main(String[] args) will work i.e the placement of [] does not matter. However, in Groovy, the former one does not work. Only String[] args will work in Groovy.
  6. As of Groovy 1.6, inner classes are not supported. They are now supported in 1.7. See this in Groovy 1.7 release notes.
  7. Even in 1.7, the behavior of inner class is not exactly the same. For example, if the nested class (B) need to refer an instance variable (say counter_) from outer class (A), in Java you can do this using A.this.counter_. This syntax does not work in Groovy.

No comments: