Question

I'm learning Groovy and came across this curious behavior. Executing the following code in groovysh works without a problem, but saving it as 'foo.groovy' and running it via groovy foo.groovy results in a MissingPropertyException: No such property: a for class: foo in line 3:

def a(n) { n*n }
def x(m) { m(2) }
x(a)

Changing a to a closure a = { n -> n*n } makes this error go away, but I'd like to avoid that for my real use case which is more complex. I've also found this question which deals with the same problem inside of a class, but the solution using this.& isn't applicable as my method isn't inside of a class, and coming from a python background I'd like to keep it that way.

What am I doing wrong? And where is this behavior documented?

Was it helpful?

Solution

It looks like groovysh stores:

def a(n) { n*n }

as a MethodClosure into a binding variable called a

This will not happen outside of groovysh, and as you have seen you'll need to define a as a closure:

def a = { n -> n*n }
def x( m ) { m( 2 ) }
x(a)

Or use the method reference operator &:

def a(n) { n*n }
def x(m) { m(2) }
x( this.&a )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top