在这段代码中,Groovy 的执行方式与 Java 不同
我查看了这个问题 这里。这个问题的问题在于这一行:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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.
如何解释一段代码中的减号是编译器的功能,它实现了语言定义。它实际上与代码实际执行的运行时系统(在本例中为 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.
在groovy 1.8下编译并运行
compiles and runs under groovy 1.8