SyntaxHighlighter

Tuesday, July 24, 2012

Calling closure in a Map

In groovy, you can store a piece of code in a Map (or even in List or whatever data structure you fancy), and call it when you want to.
It's a feature provided by closure.

For example, you can try this in groovy shell (groovysh):

groovy:000> a = [name: {return "Jack Sparrow"}]
===> {name=groovysh_evaluate$_run_closure1@26a0e990}
groovy:000> a.name
===> groovysh_evaluate$_run_closure1@26a0e990
groovy:000> a.name()
===> Jack Sparrow
groovy:000> a.name.call()
===> Jack Sparrow

But then, I was a bit confused by this:

groovy:000> a = [size: {return 5}]
===> {size=groovysh_evaluate$_run_closure1@707efa96}
groovy:000> a.size
===> groovysh_evaluate$_run_closure1@707efa96
groovy:000> a.size()
===> 1
groovy:000> a.size.call()
===> 5

Huh? Why is a.size() == 1?
I expected it to give 5.
But only when I added another closure, it dawned on me.

groovy:000> a = [age: {return 29}, size: {return 5}]
===> {age=groovysh_evaluate$_run_closure1@71257687, size=groovysh_evaluate$_run_closure2@5288d319}
groovy:000> a.age
===> groovysh_evaluate$_run_closure1@71257687
groovy:000> a.age()
===> 29
groovy:000> a.age.call()
===> 29
groovy:000> a.size
===> groovysh_evaluate$_run_closure2@5288d319
groovy:000> a.size()
===> 2
groovy:000> a.size.call()
===> 5

It might be very trivial to someone who's more familiar with groovy language, but it stumped me for a while.
Can you figure out what was going on?

No comments:

Post a Comment