splat operator in groovy?
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 开发者_如何学Ccourse.
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?
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"]
I'm not sure what you exactly want to achieve, so here are several possibilities:
If you want to add the contents from the second map to the first map, the leftShift operator is the way to go:
def foo(name, map) {
println(map)
}
def otherMap = [hi: "world"]
foo("bar", [hi: "bye"] << otherMap)
If you want to access a parameter via its name use a Map:
def foo(Map args) {
println args.map
}
def otherMap = [hi: "world"]
foo(name:"bar", first:[hi: "bye"], map:otherMap)
If you want to print all or only the last parameter use varargs:
def printLast(Object[] args) {
println args[-1]
}
def printAll(Object[] args) {
args.each { println it }
}
def printAllButName(name, Map[] maps) {
maps.each { println it }
}
def otherMap = [hi: "world"]
printLast("bar", [hi: "bye"], otherMap)
printAll("bar", [hi: "bye"], otherMap)
printAllButName("bar", [hi: "bye"], otherMap)
精彩评论