Search code examples
kotlinextension-methods

Kotlin duplicate items in list to create a new list of different objects with the same data


I have two data structures:

data class MyObjectA(val foo: String, val barA: String, val barB: String)
data class MyObjectB(val foo: String, val bar: String)

And I have a list with MyObjectA items:

val mylistA = listOf(
    MyObjectA("aaa", "bbb", "ccc"), 
    MyObjectA("ddd", "eee", "fff")
)

I want to get a list with each object repeated, but each new item containing only some of the original data:

val mylistB = listOf(
    MyObjectB("aaa", "bbb"),
    MyObjectB("aaa", "ccc"),
    MyObjectB("ddd", "eee"), 
    MyObjectB("ddd", "fff")
)

Is there some extension function in Kotlin to do it in short?


Solution

  • I would do it like this:

    data class MyObjectA(val foo: String, val barA: String, val barB: String) {
        fun toB() = listOf(MyObjectB(foo, barA), MyObjectB(foo, barB))
    }
    data class MyObjectB(val foo: String, val bar: String)
    
    fun main() {
        val mylistA = listOf(
            MyObjectA("aaa", "bbb", "ccc"),
            MyObjectA("ddd", "eee", "fff")
        )
    
        val myListB = mylistA.flatMap { it.toB() }
    
        println(myListB)
    }
    

    If you don't want to add the toB() function to the data class you can of course also do it directly like

    val myListB = mylistA.flatMap { listOf(MyObjectB(it.foo, it.barA), MyObjectB(it.foo, it.barB)) }