Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass list of objects as individual parameters

I have two methods - named one and two. Method one takes a List<Person> where person is some class and method two takes individual objects of Person class.

How can I pass the List<Person> as individual object parameters to method two? The List could contain 0 or 1 or more elements and I want to pass null if the list doesn't have all the 3 params required by method two.

def one (List<Person> persons) {

    // check the size of the list
    // pass arguments to method two

    // this works
    two(persons[0], persons[1], persons[2])

    //what I want is 
    two(persons.each { it  + ', '})
}

def two (Person firstPerson, Person secondPerson, Person thirdPerson) {

    // do something with the persons
}
like image 433
biniam Avatar asked Dec 31 '15 10:12

biniam


2 Answers

Use:

two(*persons)

* will split the list and pass its elements as separate arguments.

It will be:

def one (List<String> strings) {
    two(strings[0], strings[1], strings[2])
    two(*strings)
}

def two (String firstPerson = null, String secondPerson = null, String thirdPerson = null) {
   println firstPerson
   println secondPerson
   println thirdPerson 
}

one(['a','b','c'])
like image 148
Opal Avatar answered Sep 20 '22 23:09

Opal


You can use the spread operator * for your calling method, but based on your comment "The List could contain 0 or 1 or more elements" you will want to use the variadic function for your second method. Try this:

// Spread operator "*"
def one(List<Person> persons) {
  two(*persons)
}

//  Variadic function "..."
def two(Person... values) {
  values.each { person ->
    println person
  }
}

Now you can call the two method passing null, an empty list, or any number of Person instances such as:

two(null)
two([])
two(person1, person2, person3, person4, person5)
like image 10
dspano Avatar answered Sep 21 '22 23:09

dspano