在这段代码中,Groovy 的执行方式与 Java 不同

发布于 2024-12-12 08:25:58 字数 887 浏览 0 评论 0原文

我查看了这个问题 这里。这个问题的问题在于这一行:

Integer i3 = (Integer) -128; /*** Doesn't compile ***/

正如一些答案所说:

The compiler interprets the - as the two-arg minus operator, i.e. it's trying to subtract 128 from some other number named Integer, but there's no such variable in scope

答案对我来说看起来是正确的。现在,在 groovy 中,我尝试了与之前相同的代码:

Integer i3 = (Integer) -128; /*** compiles!!! ***/

甚至该行代码也可以编译:

Integer i3 = (Integer) -(128); /*** compiles ***/

Groovy 如何执行此操作?所有 JVM 语言都这样做吗? Groovy 的幕后发生了什么。

这不违反Java规则吗?有点困惑。

作为参考,我已在此处标记了工作 Groovy 代码,

提前致谢。

I had a look at this question here. The problem with this question is this line:

Integer i3 = (Integer) -128; /*** Doesn't compile ***/

As some of the answer's say's:

The compiler interprets the - as the two-arg minus operator, i.e. it's trying to subtract 128 from some other number named Integer, but there's no such variable in scope

The answers look correct for me. Now in groovy I tried the same code as such before :

Integer i3 = (Integer) -128; /*** compiles!!! ***/

even this code of line compiles:

Integer i3 = (Integer) -(128); /*** compiles ***/

How does Groovy performing this operation? Does all Jvm languages does this? Whats happening behind the scene's in case of Groovy.

Does this doesn't break Java rule? Bit confused.

For reference I have tagged the working Groovy code here

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

此生挚爱伱 2024-12-19 08:25:58

Groovy 不是 Java。

它不必遵循 Java 的规范,在这种情况下......不需要。

编辑清楚:我认为让您感到困惑的是您不明白这是两种不同的语言。 Groovy 编译器和 Java 编译器都会从源代码中输出字节码,然后在 JVM(Java 虚拟机)上运行。 JLS(Java 语言规范)仅适用于Java 语言。 Groovy 不必遵守它。

Groovy isn't Java.

It doesn't have to follow Java's specification and in this case ... doesn't.

Edit for clarity: I think what's confusing you is that you don't understand that these are two different languages. Both the Groovy compiler and the Java compiler output bytecode from your source code which then runs on the JVM (Java Virtual Machine). The JLS (Java Language Specification) applies to the Java language only. Groovy does not have to adhere to it.

浮世清欢 2024-12-19 08:25:58

如何解释一段代码中的减号是编译器的功能,它实现了语言定义。它实际上与代码实际执行的运行时系统(在本例中为 JVM)无关。因此,不同的语言可以具有相同的符号/关键字等,其行为方式也不同。

How to interpret a minus sign in a piece of code is a function of the compiler, which implements a language definition. It really has no bearing on the runtime system in which the code will actually execute - in this case, the JVM. So different languages can have the same symbols/keywords etc. behave in different ways.

一页 2024-12-19 08:25:58
Integer i3 = (Integer) -128;
println i3

在groovy 1.8下编译并运行

Integer i3 = (Integer) -128;
println i3

compiles and runs under groovy 1.8

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文