3

Given this Groovy program:

def f(x) { return x }

g = f

println g(42)

When feeding the program to the Groovy (version 2.4.12) interpreter, an error message is printed:

groovy.lang.MissingPropertyException: No such property: f for class: x at x.run(x.groovy:3)

However, changing the program to

def f = { x -> x }

g = f

println g(42)

Makes the interpreter print '42', as expected.

Why are these two definitions of f treated differently? Is there a way to adjust the definition of g such that the former version runs (maybe using the &. operator)?

Opal
  • 81,889
  • 28
  • 189
  • 210
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207

1 Answers1

5

With:

def f(x) { return x }

you define a method which is not an object whereas with:

def f = { x -> x }

you define a closure which is an object in terms of groovy.

These are not equivalent beings. see here.

You can indeed use & operator (in turns a method into closure):

def f(x) { return x }

def g = this.&f

println g(42)
Opal
  • 81,889
  • 28
  • 189
  • 210
  • Ah, I see - I didn't realise that methods are not objects in the Groovy sense! Thanks, that explains it. And indeed, using `this.&f` works. – Frerich Raabe Sep 21 '17 at 08:09