OK999
OK999

Reputation: 1399

Groovy method that takes multiple arguments of type Maps

i have a groovy method that works with hard coded variable of map containing maps. I would like to make, such that the maps are passed as arguments. The number of maps will vary as well. A simple representation that i am trying to achieve will be like so:

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
        }
   }
 }
}

And example of the Map of maps that i would need to pass as Args looks like so:

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

Then down the line, i would like to call something like

name(persons)

how can i achieve this? My test so far in the groovyConsole isn't taking me anywhere...

Upvotes: 0

Views: 2889

Answers (2)

Tiago Lopo
Tiago Lopo

Reputation: 7959

The problem is that you're passing a list to varArgs, you have to use *(list) to extract each element out of the list and pass them:

Example:

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))

Note: I am not quite sure I am using the right terminology but I hope you get the gist :)

Upvotes: 1

Roland
Roland

Reputation: 487

I think the problem is, that you don't have a map of maps but a list of maps. So to be able to call your method with the persons as parameter you have to change its signature to:

def map(List p) {
    ...
}

This is my snippet in the 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)

Upvotes: 1

Related Questions