Groovy方法,它接受类型为Maps的多个参数

时间:2017-03-24 00:22:40

标签: groovy

我有一个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示例,因为Args看起来像这样:

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

然后下线,我想打电话给

name(persons)

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

2 个答案:

答案 0 :(得分:1)

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

def map(List p) {
    ...
}

这是我在groovyConsole中的代码片段:

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)

答案 1 :(得分:1)

问题在于您将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))

注意:我不太确定我使用的是正确的术语,但我希望你能得到主旨:)