Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

415
Vistas
Populate a list in Kotlin with a for loop

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
}
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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)
}
over 4 years ago · Santiago Trujillo Denunciar

0

You might be looking for Kotlin Map

Example:

course.map { Courses(it.pathID, it.pathName,it.pathDescription) }
over 4 years ago · Santiago Trujillo Denunciar

0

You're getting the list with only on object, cause the function listOf(crs) returns a list of all objects that are passed as a parameters. Saying the same thing in Java you're doing something like this:

for (course: Courses) {
    Course course = new Course(...);
    List<Course> list = new ArrayList<>();
    list.add(course);
    return list;
}

As you can see the it created new list with a single object per iteration. What you're trying to achieve, can be done with operator map{...} which simply transforms every object in the initial list using code passed inside map and returns list of transformed objects

course.map{ Courses(...) }

Also, I've noticed that you're using the !! operator when creating a Courses object. Probably because the Course can have nullable name, while Courses can't. I'm considering this as a bad practice, cause in this case you're saying

Please throw an Exception if the name is null.

I think that a much better approach is to provide an alternative, like:

val name = course.name ?: "default", saying

Please use name or "default" if the name is null.

or skip objects without name, or any other approach that suits your situation.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda