'f(x){return x}'与'f = {x - > x}'有什么不同?

Fre*_*abe 3 groovy function

鉴于这个Groovy程序:

def f(x) { return x }

g = f

println g(42)
Run Code Online (Sandbox Code Playgroud)

将程序提供给Groovy(版本2.4.12)解释程序时,将打印一条错误消息:

groovy.lang.MissingPropertyException:没有这样的属性:f表示类:x at x.run(x.groovy:3)

但是,将程序更改为

def f = { x -> x }

g = f

println g(42)
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,使解释器打印为"42".

为什么这两种定义的f处理方式不同?有没有办法调整g前一个版本运行的定义(可能使用&.运算符)?

Opa*_*pal 5

附:

def f(x) { return x }
Run Code Online (Sandbox Code Playgroud)

你定义一个不是对象的方法,而使用:

def f = { x -> x }
Run Code Online (Sandbox Code Playgroud)

你定义一个闭包,它是一个groovy对象.

这些不是等同的存在.看到这里.

你确实可以使用&operator(依次将一个方法转换为闭包):

def f(x) { return x }

def g = this.&f

println g(42)
Run Code Online (Sandbox Code Playgroud)