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

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

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 中可能存在一个简单的 bug,这个 bug 可能没有被注意到,或者在后续版本的 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.html
匿名

发表评论

匿名网友

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

确定