Groovy Magic

groovy> a = '4'
groovy> b = '5'
groovy> println a + b 
45

groovy> println a.asType(int) + b.asType(int) 
105

groovy> // WTF?
groovy> println a.asType(int)
52

groovy> println b.asType(int)
53

groovy> // leave long and prosper ASCII
groovy> println a as int + b as int
expecting EOF, found '+'

groovy> println (a as int) + (b as int)
Cannot invoke method plus() on null object

groovy> a = a as int
groovy> b = b as int
groovy> println a + b
9

groovy> // w00t!

Comments

1. On Wednesday 10 December 2008, 23:00 by Tweety

Wizard Bonvillain.

2. On Thursday 11 December 2008, 02:07 by Nils Kassube

groovy> println (a as int) + (b as int)

Cannot invoke method plus() on null object
That happened because println is nothing special, just a method call. So it has a higher priority than the plus, i.e.
println((a as int) + (b as int))
works. If you are not sure about operator preferences, you can always use paranthesis.

3. On Thursday 11 December 2008, 11:50 by Florent

And you criticized ruby :-) You decided to put a bit of exotism in your work?

4. On Thursday 11 December 2008, 11:54 by Damien B

Thanks, nice to know that println isn't handled separately. So now the question is, from a grammar point of view, does "println((a as int) + (b as int))" mean:

- println called with (a as int) + (b as int) as a parameter and the optionnal parenthesis used

or

- println called with ((a as int) + (b as int)) with the optionnal parenthesis left off?
"If you are not sure about operator preferences, you can always use paranthesis."
I know my operator preferences, I didn't know that Groovy chose the path of C# ambiguation.

5. On Thursday 11 December 2008, 11:57 by Damien B

@Florent: forced by a lazy customer :)

6. On Sunday 14 December 2008, 11:35 by Florent

They all are :-)