将闭包应用为类方法

时间:2013-11-18 19:57:34

标签: groovy closures

假设有一个函数def f = { x -> x + 4 }

有没有办法像7.f()那样称呼它并获得11

1 个答案:

答案 0 :(得分:5)

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

Integer.metaClass.f = { delegate + 4 }

assert 7.f() == 11
相关问题