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!
Groovy Magic
mercredi 10 décembre 2008. Lien permanent Cyberpunk
6 réactions
1 De Tweety - 10/12/2008, 23:00
Wizard Bonvillain.
2 De Nils Kassube - 11/12/2008, 02:07
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 De Florent - 11/12/2008, 11:50
And you criticized ruby :-) You decided to put a bit of exotism in your work?
4 De Damien B - 11/12/2008, 11:54
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 De Damien B - 11/12/2008, 11:57
@Florent: forced by a lazy customer :)
6 De Florent - 14/12/2008, 11:35
They all are :-)