【问题标题】:Groovy method that takes multiple arguments of type Maps采用 Maps 类型的多个参数的 Groovy 方法
【发布时间】:2017-03-24 00:22:39
【问题描述】:

我有一个 groovy 方法,它适用于map containing maps 的硬编码变量。我想做这样的地图作为参数传递。地图的数量也将vary。我试图实现的一个简单表示是这样的:

def name(Map p...) {
 //code to loop through each of the maps 
    p.each { k ->
      "${k.first}, ${k.last}"
 //another loop with the internal map
    something { 
       k.details.each { name, value ->
  //some code
        }
   }
 }
}

我需要传递的 Map of maps 示例如下:

def persons = [
[first: 'Jack', last: 'Smith', details: [gender: 'male', Age: 25]], 
[first: 'Sean', last: 'Dean', details: [gender: 'male', Age: 26]]
]

那么接下来,我想调用类似的东西

name(persons)

我怎样才能做到这一点?到目前为止,我在 groovyConsole 中的测试并没有带我去任何地方......

【问题讨论】:

  • 您介意解释一下您遇到的确切问题吗?
  • 似乎传递了一个列表name(persons),而不是方法中定义的映射。
  • 是的,这似乎是一个原因......我忽略了它

标签: groovy


【解决方案1】:

我认为问题在于,您没有地图地图,而是地图列表。因此,为了能够以 people 作为参数调用您的方法,您必须将其签名更改为:

def map(List p) {
    ...
}

这是我在 groovyConsole 中的 sn-p:

def persons = [
    [first: 'Jack', last: 'Smith', details: [gender: 'male', Age: 25]], 
    [first: 'Sean', last: 'Dean', details: [gender: 'male', Age: 26]]
]

class Person {
    def name(List p) {
        println p
    }
}

def p = new Person()
p.name(persons)

【讨论】:

    【解决方案2】:

    问题是您将list 传递给varArgs,您必须使用*(list) 从列表中提取每个元素并传递它们:

    例子:

    def name( Map... p ) { 
      p.each{ println it} 
    }
    
    def persons = [
    [first: 'Jack', last: 'Smith', details: [gender: 'male', Age: 25]], 
    [first: 'Sean', last: 'Dean', details: [gender: 'male', Age: 26]]
    ]
    
    name(*(persons))
    

    注意:我不太确定我是否使用了正确的术语,但我希望你能明白要点:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2011-01-14
      • 1970-01-01
      相关资源
      最近更新 更多