It's been a while that I just started to learn how to develop in Kotlin. There is this thing that I am working on, I am trying to parse a list into another type of list. Basically they are the same thing but with different names. But when I try to populate the new list with the data that I get from the list given as parameter in the function the list only gets populated with the first object.
Here is my function:
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
}
List iteration or list looping is the process of going through the list elements one by one. Here is a complete source code to demonstrate five ways of looping over a list in Kotlin. The forEach () performs the given action on each list element. We pass it an anonymous function that prints the current element - We loop the list with for.
len – 1, where ‘len’ is the length of the list. We can retrieve the first and the last elements of the list without using the get () method. It is process of accessing the elements of list one by one. There are several ways of doing this in Kotlin. The for loop traverses the list.
The indexOf () method returns the index of the first occurrence of the specified element in the list, or -1 if the specified element is not contained in the list. When you run the above Kotlin program, it will generate the following output: The get () method can be used to get the element at the specified index in the list.
Kotlin mutable or immutable lists can have duplicate elements. For list creation, use the standard library functions listOf () for read-only lists and mutableListOf () for mutable lists.
The error in your code is that you are making a list in every iteration of the loop. You should make the list first and then add every item from the loop to it!
fun convertRoomClass(courses: List<Course>) : List<AnotherCourseClass> {
val newList = mutableListOf<AnotherCourseClass>()
courses.forEach {
newList += AnotherCourseClass(it.pathID, it.pathName, it.pathDescription)
}
return newList
}
A better solution is to use the map function
fun convertRoomClass(courses: List<Course>) = courses.map {
AnotherCourseClass(it.pathID, it. pathName, it.pathDescription)
}
You might be looking for Kotlin Map
Example:
course.map { Courses(it.pathID, it.pathName,it.pathDescription) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With