1

我是 groovy 和研究类型强制的新手。

添加两个字节时有一些奇怪的操作。据我所知,groovy 将两个字节的加法转换为整数。但如果有括号,它仍然是字节。

assert (Byte)1 + (Byte)2 instanceof Integer
assert ((Byte)1 + (Byte)2) instanceof Byte

我在 groovy 2.1.4 上对其进行了测试,但无法理解其中的区别。

我在这里先向您的帮助表示感谢。

4

1 回答 1

2

(Byte)1 + (Byte)2无论括号如何,都会导致字节类型。

(Byte)1 + (Byte)2 instanceof Integer失败,因为它会首先将“2 instanceof Integer”评估为 true,然后尝试将 true 强制转换为 Byte,从而导致强制转换异常。

2014 年 1 月 1 日更新:我仔细看了看,因为这是一个关于为什么断言也不会产生强制转换错误的有效问题,这就是我发现的。鉴于此脚本:

(Byte)1+(Byte)2 instanceof Integer
assert (Byte)1+(Byte)2 instanceof Integer

根据文档,Groovy 编译器解析脚本并基于语法创建代码的 AST 表示。第一行被解析为ExpressionStatement(特别是 a CastExpression),但第二行被解析为AssertStatement. AssertStatementGroovy 的 AST 中的An有一个BooleanExpression孩子,似乎没有澄清括号,这会影响它决定解析代码的方式......这两行最终看起来像这样:

((1 + ((2) as Byte) instanceof Integer) as Byte)
assert ((1) as Byte) + ((2) as Byte) instanceof Integer : null

这就是为什么当另一个导致 GroovyCastException 时断言运行并最终为真的原因。我不确定这是否是一个错误......我想我会在 Groovy 论坛上提问。

于 2013-12-24T03:52:43.183 回答