Home > Back-end >  Is there a way in Kotlin to map through a list, referencing previous values of the new transformatio
Is there a way in Kotlin to map through a list, referencing previous values of the new transformatio

Time:12-18

Pretty much the title. I want to map through a list to create a new list, but the logic for transforming each element depends on previous values that have been already transformed.

For a simple example, I have a list val myList = [1, 2, 3, 4, 5] and I want to map through each value, where each new value is the sum of the current element plus the previous transformed element. Meaning, I want the result to be [1, 3, 6, 10, 15]. This is not a real scenario, just for sake of example.

I can map through my list but I don't know how to reference the new list that's currently being built:

myList.map { it   list_that's_currently_being_built[i-1] }

CodePudding user response:

runningReduce

fun main() {
    val myList = listOf(1, 2, 3, 4, 5)

    val result = myList.runningReduce { acc, value -> acc   value }

    println(result) // [1, 3, 6, 10, 15]
}
  • Related