Most Java code is also syntactically valid Groovy code. However, there are a few exceptions which leads me to my question:
Which constructs/features in Java are syntactically invalid in Groovy? Please provide concrete examples of Java code (Java 1.6) that is NOT valid Groovy code (Groovy 1.6).
Update:
So far we’ve got five examples of syntactically valid Java code that is not valid Groovy code:
- Array initializations
- Inner classes
defis a keyword in Groovy, but not in Java'$$'-strings – parsed as an invalidGStrings in Groovy- Non-static initialization blocks
-- class Foo { Integer x; { x = 1; } }
Is this the complete list? Any further examples?
Update #1: I’ve started a bounty to bump this question. The bounty will be granted to the person who provides the most comprehensive list of examples. So far we’ve uncovered five examples, but I’m sure there a quite some more out there. So keep them coming!
Here is a list of items that are valid Java 6, but not valid Groovy 1.6. This isn’t a complete list, but I think it covers most of the cases. Some of these are permitted by later Groovy versions as noted below.
(By the way, I think you should note that non-static initialization blocks DO work in Groovy.)
Any inner class declaration in Groovy 1.6 (1.7 added inner classes):
including static,
non-static,
local classes,
and anonymous classes
Using Groovy keywords as variables won’t work in any Groovy version:
Java array initialization
Use the Groovy array-literal format by changing
{...}to[...].Using dollar signs in strings where what follows isn’t a valid expression
More than one initializer in a for loop
More than one increment in a for loop
Breaking up some expressions using newlines
Hint: use a backslash line-continuation in Groovy
Ending switch with a case that has no body
Having a default in a switch with no body
Applies in both cases where default is at the end
or somewhere in the middle
Annotations with lists
Hint: use Groovy list-literal syntax instead:
Native method declaration
**Class per enum in 1.6 (valid in later Groovy versions) **
Do loop
Equality
While technically
==is valid Groovy and Java, it’s semantically different. It’s one of the reasons you can’t rely on just compiling Java as Groovy without changes. Worse, it might seem to work sometimes due to Java string interning.The example was too long to add to an existing answer, but the point is that Java code that’s syntatically valid as Groovy might behave differently at runtime.
To get the same result as Java’s
x == yfor two not-null objects you needx.is(y)in Groovy.x == yis valid Groovy, it just does something different.The Groovy documentation has a more detailed and broader list of differences.