Reputation: 15018
In Java I can do this:
return a
&& b
&& c;
In Groovy, it returns a compile error: unexpected token: &&
. It also occurs if I omit the return
keyword in Groovy. However if I wrap the statement in parentheses, it works fine.
In all the Groovy resources I've read, I've been told that I should be able to write "straight Java" wherever I want. Is this a bug? If not, what is the reason for this design decision?
I looked here, but did not find this issue listed. I understand that there are some things that cannot be inherited from Java, but this wouldn't seem like one of those things.
Upvotes: 13
Views: 3084
Reputation: 2349
you can do almost all java in groovy except you look at the following.
http://groovy.codehaus.org/Differences+from+Java
if you want to do straight java then you can do it in a *.java class and drop it into the src folder.
Upvotes: 2
Reputation: 1500465
The problem is that Groovy doesn't require explicit line terminators - and return a
looks like a valid statement on its own. You could use:
return a &&
b &&
c;
Or use a line continuation:
return a \
&& b \
&& c;
It's not true that all Java is valid Groovy. While most Java syntax is covered, occasionally a feature of Groovy will have an impact on valid Java.
Upvotes: 25
Reputation: 54242
Groovy doesn't seem to require semicolons, so I think your code is being intepreted like:
return a;
&& b;
&& c;
From the documentation:
Groovy uses a similar syntax to Java although in Groovy semicolons are optional.
This saves a little typing but also makes code look much cleaner (surprisingly so for such a minor change). So normally if one statement is on each line you can ommit semicolons altogether - though its no problem to use them if you want to. If you want to put multiple statements on a line use a semicolon to separate the statements.
Upvotes: 9