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
}
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'])
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With