Groovy 将对象列表作为单个参数传递

Groovy 将对象列表作为单个参数传递,groovy,parameters,Groovy,Parameters,我有两种方法-命名为one和two。方法one获取一个List,其中person是某个类,方法two获取person类的单个对象 如何将列表作为单个对象参数传递给方法two? 列表可能包含0个或1个或多个元素,如果列表没有方法two所需的全部3个参数,我希望传递null def one (List<Person> persons) { // check the size of the list // pass arguments to method two

我有两种方法-命名为
one
two
。方法
one
获取一个
List
,其中
person
是某个类,方法
two
获取
person
类的单个对象

如何将
列表作为单个对象参数传递给方法
two
列表
可能包含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
}
def one(列出人员){
//检查列表的大小
//将参数传递给方法2
//这很有效
两(人[0],人[1],人[2])
//我想要的是
两人(每人{it+',})
}
def 2(第一人、第二人、第三人){
//对这些人做点什么
}
使用:

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

它将是:

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'])
def one(列出字符串){
两个(字符串[0],字符串[1],字符串[2])
两个(*字符串)
}
def 2(字符串firstPerson=null,字符串secondPerson=null,字符串thirdPerson=null){
第一人称
第二人
第三个人
}
一个(['a','b','c'])

您可以对调用方法使用扩展运算符*,但根据您的注释“列表可能包含0个或1个或多个元素”,您将希望对第二个方法使用可变函数。试试这个:

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

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

美好的几乎是对的,但是如果只有两个论点呢?一个(['a','b'])。biniam希望将null作为缺少的一个。幸运的是,Groovy中有默认参数,所以完整的解决方案是两个(String firstPerson=null,String secondPerson=null,String thirdPerson=null),我避免使用大写参数名,即
persons
,而不是
persons
。大写有时会让您感到悲伤,因为groovy有时会猜到您在使用示例更改正确的类名时犯了一个classIt重构错误。我在日常编程中不这样做。我编辑了这个问题
// Spread operator "*"
def one(List<Person> persons) {
  two(*persons)
}

//  Variadic function "..."
def two(Person... values) {
  values.each { person ->
    println person
  }
}
two(null)
two([])
two(person1, person2, person3, person4, person5)