我们采用以下简单的表达式:
((Double) null ?: 0).getClass()
结果:
class java.lang.Double
class java.lang.Integer
有人知道不同行为的原因吗? 我认为 Groovy 4 是正确的,因为转换是在 Elvis 运算符之前应用的。
已检查,但在 Groovy 4 发行说明中找不到任何相关内容:https://groovy-lang.org/releasenotes/groovy-4.0.html
从文档来看, ?: 的优先级比类型转换低得多。 Typecast
(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 的更高版本中修复的错误,具体取决于您用来测试它的版本。尽管它已修复,但报告它可能是值得的,这样他们就可以编写一个单元测试来在将来捕获它,因为它可能不会被注意到。