如何使用附加参数的方法制作Kotlin类
我如何制作一个 kotlin 类,它接受一个输入 arg(字符串)并将其附加到自身的增长列表中?例如,一个人可以买一只狗。人是一个类,狗的名字是一个参数。然后这个人买了第二只狗,它被附加在 Person 类中。所以你查询person.dogs,现在有两只狗。
谢谢你的帮助。
回答
有两种方法可以将元素附加到不断增长的列表中:
- 列表方法:添加新元素时,返回一个新的
ListusingList.plus方法,同时包含现有元素和较新元素 - MutableList 方法:只需
MutableList使用MutableList.add方法将新元素添加到 a 中
希望以下代码片段解释了这两种方法的工作原理:
data class PersonWithReadOnlyDogs(val dogs: List<String> = emptyList()) {
fun plusDog(newDog: String) = PersonWithReadOnlyDogs(dogs.plus(newDog))
}
data class PersonWithMutableDogs(val dogs: MutableList<String> = mutableListOf()) {
fun addDog(newDog: String) = dogs.add(newDog)
}
fun main() {
// List approach - create a new person with more dogs on each addition
val personWithFooDog = PersonWithReadOnlyDogs(listOf("foo"))
val personWithFooAndBarDogs = personWithFooDog.plusDog("bar")
// At this point personWithFooAndBarDogs has both foo and bar dogs
println(personWithFooAndBarDogs.dogs)
// MutableList approach - keep adding dogs to the same person
val person = PersonWithMutableDogs(mutableListOf("foo"))
person.addDog("bar")
// At this point person has both foo and bar dogs
println(person.dogs)
}