views:

176

answers:

3

Is Groovy a superset of Java yet? If not, what are the incompatibilities between Groovy and Java?

By superset, I mean source backward compatibility, in the sense that: you can take a Java file and compile it as Groovy source file, and it would work just as before. It has been the goal of Groovy to make very similar to Java, to minimize the learning curve. However, until Groovy 1.7 that was no support for anonymous inner classes and such.

I have seen some articles making such claim, but I haven't seen it verified on the Groovy website.

+2  A: 

Is Groovy a superset of (i.e. source compatible with) Java yet? If not, what are the incompatibilities between Java and Groovy now?

Groovy "extends" Java and there are differences between Groovy and Java (a Groovy File can not be compiled by the Java compiler). The page Differences from Java list all the major differences between Java and Groovy. That said, the Groovy Compiler can converts a Groovy File into a .class File that can be run using the Java Intepreter (this requires groovy-all-VERSION.jar to be on the CLASSPATH). Does this answer the question?

Pascal Thivent
Thanks, I updated the question to clarify my point.
notnoop
+1  A: 

One difference I didn't see mentioned on that page is the way overloaded methods are resolved. In Java, it is based on the compile-time type of an argument, whereas in Groovy it is based on the runtime type. Say for example you have these methods in a class

void doIt(Object o) {}  // Java
void doIt(String s) {}  // Groovy

The following code:

Object o = "foo";

Would invoke the method with the String parameter if Groovy code, and the method with the Object parameter if Java code. Groovy calls this feature "multi-methods".

Don
Thanks. This is known as "multi-method dynamic dispatch" in literature.
notnoop
A: 

In groovy, properties with package access (well, I should call that attributes or instance variables perhaps) get automatically setter and getter methods compiled into the class file.

That means if you save a *.java file as *.groovy file and you have an attribute like "String name;" the groovy compiler will generate a setter and a getter. The java compiler wont. If you already have a getter in your java file, the groovy compiler even might complain about a duplicated method definition.

However unless for rare cases most *.java files get compiled by the groovy compiler without issues.

Angelo

Angel O'Sphere