Groovy中的splat运算符是什么?

3
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

我该如何修复这个问题?

2
你怎么期望 foo("bar",otherMap) 打印出来的不是 bar?你正在打印第一个参数。 - Geo
@Geo 是的,我也在想同样的问题(但我是 Groovy 的新手,所以不知道)。特别是我对 OP 中的这个感到困惑: foo("bar", hi: "bye") 为什么会打印出 [hi: "bye"] 而不是 "bar"(但如果你改成 foo("bar", [hi: "bye"]))它就按预期工作了。 请问有人能解释一下吗? - inger
2个回答

8
您需要使用扩展映射运算符。
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"]

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)

如果你想打印所有或者仅最后一个参数,可以使用可变参数:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接