Is Groovy syntax an exact superset of Java syntax?
Being a Java programmer, I don't really have a Groovy background, but I use Groovy a lot lately to extend Maven (using GMaven). So far, I could use all the Java code I need in Groovy with the added Groovy sugar (metaclass methods, more operators, closures). My knowledge of Groovy is far from complete, but I like it, especially for Scripting purposes (I'm a bit careful about using a non-static typed language in an enterprise scenario,开发者_运维百科 but that's not the topic here).
Anyway, the question is:
Is every bit of valid Java code automatically valid Groovy code? (I am talking about Source code, not compiled classes, I know Groovy can interact with Java classes.) Or are there Java constructs that are illegal in Groovy? Perhaps a reserved Groovy keyword that could be used as an identifier in Java, or something else? Or has Groovy deliberately been designed to be 100%-source compatible with Java?
Nope. The following are keywords in groovy, but not Java:
any as def in with
Additionally, while not keywords, delegate
and owner
have special meaning in closures and can trip you up if you're not careful.
Additionally, there are some minor differences in the language syntax. For one thing, Java is more flexible about where array braces occur in declarations:
public static void main(String args[]) // valid java, error in groovy
Groovy is parsed differently, too. Here's an example:
public class Test {
public static void main(String[] args) {
int i = 0;
i = 5
+1;
System.out.println(i);
}
}
Java will print 6, groovy will print 5.
While groovy is mostly source compatible with java, there are lots of corner cases that aren't the same. That said, it is very compatible with the code people actually write.
It isn't.
My favorite incompatibility: literal arrays:
String[] s = new String[] {"a", "b", "c"};
In Groovy, curly braces in this context would be expected to contain a closure, not a literal array.
There's a page on the Groovy site which documents some of the differences, and another page which lists gotchas (such as the newline thing)
There are other things as well, one example being that Groovy doesn't support the do...while
looping construct
Others have already given examples of Java syntax that is illegal in Groovy (e.g. literal arrays). It is also worth remembering that some syntax which is legal in both, does not mean the same thing in both languages. For example in Java:
foo == bar
tests for identity, i.e. do foo
and bar
both refer to the same object? In Groovy, this tests for object equality, i.e. it returns the result of foo.equals(bar)
精彩评论