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

bin*_*iam 15 parameters groovy

我有两个方法 - 命名onetwo.方法one取一个类List<Person>在哪里person,方法twoPerson类的各个对象.

如何将List<Person>单个对象参数传递给方法two?在List可以包含0或1种以上的元素,我想通过null如果列表中没有的方法所需的全部3个PARAMS 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
}
Run Code Online (Sandbox Code Playgroud)

Opa*_*pal 12

使用:

two(*persons)
Run Code Online (Sandbox Code Playgroud)

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

这将是:

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'])
Run Code Online (Sandbox Code Playgroud)

  • 太好了!这几乎是正确的,但如果只有两个参数怎么办?一个(['a','b']).biniam希望将null作为缺失的.幸运的是,Groovy中有默认参数,因此完整的解决方案将是两个(String firstPerson = null,String secondPerson = null,String thirdPerson = null) (2认同)

dsp*_*ano 9

您可以使用扩展运算符*作为调用方法,但根据您的注释"列表可能包含0个或1个或更多元素",您将需要为第二个方法使用可变参数函数.试试这个:

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

//  Variadic function "..."
def two(Person... values) {
  values.each { person ->
    println person
  }
}
Run Code Online (Sandbox Code Playgroud)

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

two(null)
two([])
two(person1, person2, person3, person4, person5)
Run Code Online (Sandbox Code Playgroud)