geekslife
geekslife

Reputation: 31

groovy type coercion with parentheses

I'm new to groovy and studying type coercion.

There's some strange operation when two bytes are added. As far as I know, groovy converts two bytes' addition as integer. But if there's parentheses, it still remains as Byte.

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

I tested it on groovy 2.1.4 and can't understand the difference.

Thanks for the help in advance.

Upvotes: 1

Views: 120

Answers (1)

chrixian
chrixian

Reputation: 2811

(Byte)1 + (Byte)2 would result in a byte type, regardless of the parenthesis.

(Byte)1 + (Byte)2 instanceof Integer fails since it would first evaluate "2 instanceof Integer" to true and then try to cast true to Byte resulting in a cast exception.

UPDATE 1/1/2014: I took a closer look since it's a valid question as to why the assert doesn't produce a cast error too, here is what I found. Given this script:

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

According to the documentation, the Groovy compiler parses the script and creates an AST representation of the code based on a grammar. The first line is parsed into an ExpressionStatement (specifically a CastExpression) but the second line is parsed into an AssertStatement. An AssertStatement in Groovy's AST has a BooleanExpression child and it seems without clarifying parenthesis, this influences how it decides to parse the code... the two lines end up looking like this:

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

This is why the assert runs and ends up being true when the other results in a GroovyCastException. I'm not sure if this is a bug or not... I'm going to ask on the Groovy forum I think.

Upvotes: 2

Related Questions