gpt4 book ai didi

android - 使用 for 循环填充 Kotlin 中的列表

转载 作者:行者123 更新时间:2023-12-02 12:51:20 25 4
gpt4 key购买 nike

我刚刚开始学习如何使用 Kotlin 进行开发已经有一段时间了。我正在做这件事,我试图将一个列表解析为另一种类型的列表。基本上它们是相同的东西,但名称不同。但是,当我尝试使用从作为函数参数给出的列表中获取的数据填充新列表时,列表仅填充第一个对象。

这是我的功能:

fun convertRoomClass(course: List<Course>) : List<Courses> {

lateinit var list : List<Courses>


course.forEach {
val id = it.pathID
val name = it.pathName
val desc = it.pathDescription

val crs : Courses = Courses(id, name!!, desc!!)

list = listOf(crs)
}

return list
}

最佳答案

代码中的错误是您在循环的每次迭代中都创建了一个列表。您应该首先创建列表,然后将循环中的每个项目添加到其中!

fun convertRoomClass(courses: List<Course>) : List<AnotherCourseClass> {
val newList = mutableListOf<AnotherCourseClass>()
courses.forEach {
newList += AnotherCourseClass(it.pathID, it.pathName, it.pathDescription)
}
return newList
}

更好的解决方案是使用 map 功能

fun convertRoomClass(courses: List<Course>) = courses.map {
AnotherCourseClass(it.pathID, it. pathName, it.pathDescription)
}

关于android - 使用 for 循环填充 Kotlin 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54252308/

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