将对象列表作为单独的参数传递

Pass list of objects as individual parameters

我有两个方法 - 名为 onetwo。方法 one 采用 List<Person>,其中 person 是一些 class,方法 two 采用 Person class 的单个对象。

如何将 List<Person> 作为单独的对象参数传递给方法 twoList 可以包含 0 或 1 个或更多元素,如果列表不包含方法 two.

所需的所有 3 个参数,我想传递 null
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
}

使用:

two(*persons)

* 将拆分列表并将其元素作为单独的参数传递。

它将是:

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

您可以将扩展运算符 * 用于您的调用方法,但根据您的评论 "The List could contain 0 or 1 or more elements",您将希望对第二种方法使用可变参数函数。试试这个:

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

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

现在您可以调用这两个方法传递 null、空列表或任意数量的 Person 实例,例如:

two(null)
two([])
two(person1, person2, person3, person4, person5)