使用for循环在Kotlin中填充列表

Jon*_*ona 0 android for-loop list kotlin

一段时间以来,我才刚刚开始学习如何在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
}
Run Code Online (Sandbox Code Playgroud)

Ahm*_*azy 8

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

fun convertRoomClass(courses: List<Course>) : List<AnotherCourseClass> {
    val newList = mutableListOf<AnotherCourseClass>()
    courses.forEach {
        val id = it.pathID
        val name = it.pathName
        val desc = it.pathDescription
        newList += AnotherCourseClass(id, name, desc)
    }
    return newList
}
Run Code Online (Sandbox Code Playgroud)

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

fun convertRoomClass(courses: List<Course>) = courses.map {
   AnotherCourseClass(it.pathID, it.pathDescription, it.pathDescription)
}
Run Code Online (Sandbox Code Playgroud)


Mil*_*ada 6

您可能正在寻找 Kotlin地图

例子:

course.map { Courses(it.pathID, it.pathName,it.pathDescription) }
Run Code Online (Sandbox Code Playgroud)