ja6a
ja6a

Reputation: 416

Elegant Kotlin Object Enriching

I would like to output an object based upon an input object. I want to enrich it by populating an empty array contained within the input object. The new array is based on an existing array contained in the object. The output object is deep equal to the input object except it contains the new array. I have developed the following code block:

fun enrich(a: T1) {
    val b = mutableListOf<T1>()
    a.forEach { it1 ->
        val bb = mutableListOf<T2>()
        it1.aa.forEach { it2 ->
            val bbb = mutableListOf<T3>()
            it2.aaa.forEach { it3 ->
                bbb.add(T3("somevalue based upon it3"))
            }
            bb.add(T2(bbb))
        }
        b.add(T1(aa, bb))
    }
    return b
}

Is there a more elegant solution?

Upvotes: 0

Views: 249

Answers (1)

Eugene Popovich
Eugene Popovich

Reputation: 3473

You can use map method. So the final solution may look like this

fun enrich(a: MutableList<T1>): MutableList<T1> {
    return a.map { it1 ->
        T1(it1.aa.map { it2 ->
            T2(it2.aaa.map { it3 ->
                T3("somevalue based upon $it3")
            })
        })
    }.toMutableList()
}

Upvotes: 2

Related Questions