groovy 中的 splat 运算符?
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
如何解决此问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在寻找展开地图运算符。
印刷:
You're looking for the spread-map operator.
prints:
我不确定您到底想要实现什么,所以这里有几种可能性:
如果您想将第二个地图中的内容添加到第一个地图中,则 leftShift 运算符是正确的方法:
如果您想通过参数访问参数name 使用 Map:
如果要打印所有参数或仅打印最后一个参数,请使用 varargs:
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:
If you want to access a parameter via its name use a Map:
If you want to print all or only the last parameter use varargs: