Apply closure as a class method

Suppose there is a function def f = { x -> x + 4 }.

Is there a way to call it somehow like 7.f() and get 11?

Upvotes: 0

Views: 148

Answers (1)

Will
Will

Reputation: 14559

Yes, you can add that function as a method to the Integer class, but, instead of using the x variable, you are better using the delegate of the closure:

Integer.metaClass.f = { delegate + 4 }

assert 7.f() == 11

Upvotes: 5

Related Questions