Elvis 运算符和类型转换优先级在 Groovy 中

huangapple go评论86阅读模式
英文:

Elvis operator and type casting precedence in Groovy

问题

以下是翻译好的内容:

让我们来看下面的简单表达式:

((Double) null ?: 0).getClass()

结果:

  • Groovy 3:class java.lang.Double
  • Groovy 4:class java.lang.Integer

有人知道不同行为的原因吗?
我会说Groovy 4是正确的,因为类型转换在Elvis运算符之前应用。

检查了,但在Groovy 4的发行说明中找不到相关信息:https://groovy-lang.org/releasenotes/groovy-4.0.html

英文:

Let's take the following simple expression:

((Double) null ?: 0).getClass()

Results:

  • Groovy 3: class java.lang.Double
  • Groovy 4: class java.lang.Integer

Does anyone know the reason for the different behaviour?
I'd say Groovy 4 is correct since the casting is applied before the Elvis operator.

Checked, but couldn't find anything related in the Groovy 4 release notes: https://groovy-lang.org/releasenotes/groovy-4.0.html

答案1

得分: 0

从文档中可以看出,?: 运算符的优先级比类型转换要低得多。类型转换 (type) 的优先级为1,而 Elvis 运算符 ?: 的优先级为14,所以看起来 Groovy 4 做得对。

https://groovy-lang.org/operators.html#_operator_precedence

在 Groovy 3 的文档中也有相同的说明:

http://docs.groovy-lang.org/docs/groovy-3.0.18/html/documentation/#_operator_precedence

唯一的解释可能是在 Groovy 3 中存在一个未被注意到的简单错误,或者可能是在后续版本的 Groovy 3 中修复的错误,具体取决于你用于测试的版本。即使问题已经修复,也许还值得报告它,这样他们可以编写一个单元测试以便将来能够捕捉到类似的问题,因为它可能曾经被忽略了。

英文:

From the docs the precedence of the ?: is much lower than typecast. Typecast (type) is level 1 precedence and the elvis operator ?: is 14 so it looks like Groovy 4 is doing the right thing.

https://groovy-lang.org/operators.html#_operator_precedence

and in Groovy 3 docs it is documented the same:

http://docs.groovy-lang.org/docs/groovy-3.0.18/html/documentation/#_operator_precedence

The only way I might explain it is simple bug in Groovy 3 that went unnoticed, or maybe a bug that was fixed in later versions of Groovy 3 depending on the version you're using to test it. It might be worth it to report it even though its fixed just so they could write a unit test to catch it in the future since it possibly went unnoticed.

huangapple
  • 本文由 发表于 2023年8月9日 09:09:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76863969-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定