gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:22:46 26 4
gpt4 key购买 nike

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

如何将List<Person>作为单个对象参数传递给方法two
List可能包含0个或1个或多个元素,如果列表没有方法null所需的所有3个参数,我想通过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
}

最佳答案

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

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

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


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

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

关于groovy - 将对象列表作为单个参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34545079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com