13

在 Java 中,我可以这样做:

return a
    && b
    && c;

在 Groovy 中,它返回一个编译错误:unexpected token: &&. 如果我return在 Groovy 中省略了关键字,也会发生这种情况。但是,如果我将语句括在括号中,它就可以正常工作。

在我读过的所有 Groovy 资源中,我都被告知我应该能够在任何我想要的地方编写“纯 Java”。这是一个错误吗?如果不是,这个设计决定的原因是什么?

我看了here,但没有发现这个问题。我知道有些东西不能从 Java 继承,但这似乎不是其中之一。

4

3 回答 3

25

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.

于 2012-04-17T19:48:57.897 回答
9

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.

于 2012-04-17T19:48:53.137 回答
2

除了查看以下内容外,您几乎可以在 groovy 中执行所有 java 操作。

http://groovy.codehaus.org/Differences+from+Java

如果您想直接使用 java,那么您可以在 *.java 类中进行操作并将其放入 src 文件夹中。

于 2012-04-17T19:57:33.503 回答