Reputation: 6461
Is it possible to use a closure with the spread operator with Groovy.
e.g.
def numbers = [4,8]
def numbersPlusTen = numbers*.{it -> it + 10}
Or can the spread operator only ever work on a method or property?
Upvotes: 3
Views: 465
Reputation: 1673
Also you can use List's each() method for even more complex operation, not just plus():
list.each({item -> item.callSomeMethod(item.getSomeProperty()+1)})
so your example with implicit arg would be:
def numbersPlusTen = []
numbers.each({numbersPlusTen << it+10})
spread operator may also be used in front:
def args = [4,8]
function f(int x, int y) {x+y}
f(*args)
Upvotes: 0
Reputation: 50245
Or I would just do
def numbers = [4,8]
def numbersPlusTen = numbers*.plus(10)
if I want to add 10. :)
Upvotes: 4
Reputation: 24776
No, the spread dot operator only works on methods. However in your example you can use some meta programming to make this work.
def numbers = [4,8]
java.lang.Integer.metaClass.something = {delegate + 10}
def numbersPlusTen = numbers*.something()
Upvotes: 3