Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy vs. Java syntax discrepancy

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.

like image 576
Travis Webb Avatar asked Apr 17 '12 19:04

Travis Webb


People also ask

Can I use Java syntax in Groovy?

Groovy scripts can use any Java classes. They can be compiled to Java bytecode (in . class files) that can be invoked from normal Java classes. The Groovy compiler, groovyc, compiles both Groovy scripts and Java source files, however some Java syntax (such as nested classes) is not supported yet.

How is Groovy different than Java?

Groovy is a dynamic typing language, while Java is a statically typed language. Thus, with Groovy programming, developers can spend less time writing code. When writing code in Java, developers must finish every statement with a semicolon. In Groovy, semicolons are optional.

What is the advantage of Groovy over Java?

Groovy is a Java enhancer because it provides greater flexibility and even introduces special features to applications (those that have already been developed can be improved or they can be made from scratch). Groovy is a Java-like syntax, but with the ease of more moldable languages like Python and Ruby.

Is Groovy faster than Java?

"With the @CompileStatic, the performance of Groovy is about 1-2 times slower than Java, and without Groovy, it's about 3-5 times slower.


1 Answers

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.

like image 190
Jon Skeet Avatar answered Sep 27 '22 19:09

Jon Skeet