Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin – How to convert a list of objects into a single one after map operation?

I’m trying to wrap my head around map and reduce operations in Kotlin. At least, I guess it’s reduce what I’m trying to do.

Let’s say that I have a class called Car that takes any number (varargs constructor) of CarPart. Then, I have a list of CarPart which I’ll do a map operation and from the result of the operation I need to build one Car using each subelement, something along these lines:

class CarPart(val description: String)
class Car(vararg val carPart: CarPart)

val carParts = listOf(CarPart("Engine"), CarPart("Steering Wheel")))

carParts.map { it.description.toUpperCase() }
    .map { CarPart(it) }
    .reduce { acc, carPart -> Car(carPart) }  <--- I'm struggling here, is reduce what I should be doing 
                                                   to construct one car from all the subelement?

PS.1: I know that the class design could be better and not take a varargs, this is just an example of a legacy application I’m refactoring and originally that’s a Java class taking varargs which I can’t change now.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

PS.2: The example of mapping to a String and then creating an object out of that String is just for the sake of the example. The actual code grabs an object within the list.

>Solution :

You can simply use a the spread operator (*) over an array:

val mappedCarParts = carParts
    .map { it.description.toUpperCase() }
    .map { CarPart(it) }
    .toTypedArray()

val car = Car(*mappedCarParts)

// Or even:

val car = carParts
    .map { it.description.toUpperCase() }
    .map { CarPart(it) }
    .toTypedArray()
    .let{ Car(*it) }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading