Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splat operator in groovy?

Tags:

groovy

dsl

def foo(map, name) {
  println(map)
}

foo("bar", hi: "bye")

will print

[hi:bye]

Now I have a previous map that I wish to pass along to foo. In pseudo code, something like:

def otherMap = [hi: "world"]
foo("bar", hi: "bye", otherMap*)

So that it prints

[hi:world]

This doesn't work of course.

Also, trying to pass just the map mixes the order of arguments:

def otherMap = [hi: "world"]
foo("bar", otherMap)

will print

bar

How can I fix this?

like image 423
IttayD Avatar asked Feb 06 '26 02:02

IttayD


1 Answers

You're looking for the spread-map operator.

def foo(map, name) {
  println(map)
}

foo("bar", hi: "bye")

def otherMap = [hi: "world"]
foo("bar", hi: "bye", *:otherMap)
foo("bar", *:otherMap, hi: "bye")

prints:

["hi":"bye"]
["hi":"world"]
["hi":"bye"]
like image 91
John Stoneham Avatar answered Feb 09 '26 09:02

John Stoneham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!