def foo(map, name) {
println(map)
}
foo("bar", hi: "bye")
将打印
[hi:bye]
现在我有一张我希望传递给foo的先前地图。在伪代码中,类似于:
def otherMap = [hi: "world"]
foo("bar", hi: "bye", otherMap*)
打印
[hi:world]
这当然不起作用。
此外,尝试仅传递地图会混合参数的顺序:
def otherMap = [hi: "world"]
foo("bar", otherMap)
将打印
bar
我该如何解决这个问题?
答案 0 :(得分:7)
您正在寻找传播地图运营商。
def foo(map, name) {
println(map)
}
foo("bar", hi: "bye")
def otherMap = [hi: "world"]
foo("bar", hi: "bye", *:otherMap)
foo("bar", *:otherMap, hi: "bye")
打印:
["hi":"bye"]
["hi":"world"]
["hi":"bye"]
答案 1 :(得分:0)
我不确定你想要达到的目标,所以这里有几种可能性:
如果您要将第二张地图中的内容添加到第一张地图,leftShift运算符就可以了:
def foo(name, map) {
println(map)
}
def otherMap = [hi: "world"]
foo("bar", [hi: "bye"] << otherMap)
如果您想通过名称访问参数,请使用Map:
def foo(Map args) {
println args.map
}
def otherMap = [hi: "world"]
foo(name:"bar", first:[hi: "bye"], map:otherMap)
如果要打印全部或仅打印最后一个参数,请使用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)