代码之家  ›  专栏  ›  技术社区  ›  IttayD

在groovy中展开操作符?

  •  3
  • IttayD  · 技术社区  · 16 年前
    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 回复  |  直到 16 年前
        1
  •  7
  •   John Stoneham    16 年前

    你在找地图接线员。

    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"]
    
        2
  •  0
  •   Christoph Metzendorf    16 年前

    我不确定你到底想要达到什么目标,所以这里有几个可能性:

    如果要将第二个映射的内容添加到第一个映射,则 leftShift 接线员是前进的道路:

    def foo(name, map) {
      println(map)
    }
    
    def otherMap = [hi: "world"]
    foo("bar", [hi: "bye"] << otherMap)
    

    如果要通过参数的名称访问参数,请使用映射:

    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)