将闭包应用为类方法

ДМИ*_*КОВ 0 groovy closures

假设有一个功能def f = { x -> x + 4 }.

有没有办法以某种方式称它为7.f()和得到11

Wil*_*ill 5

是的,您可以将该函数作为方法添加到Integer类中,但是x,您最好使用delegate闭包来代替使用变量:

Integer.metaClass.f = { delegate + 4 }

assert 7.f() == 11
Run Code Online (Sandbox Code Playgroud)