bin*_*iam 15 parameters groovy
我有两个方法 - 命名one和two.方法one取一个类List<Person>在哪里person,方法two取Person类的各个对象.
如何将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)
您可以使用扩展运算符*作为调用方法,但根据您的注释"列表可能包含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)
| 归档时间: |
|
| 查看次数: |
12266 次 |
| 最近记录: |