In Kotlin, how do you modify the contents of a list while iterating

前端 未结 2 472
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-24 11:20

I have a list:

val someList = listOf(1, 20, 10, 55, 30, 22, 11, 0, 99)

And I want to iterate it while modifying some of the values. I kn

2条回答
  •  抹茶落季
    2020-12-24 11:51

    Here's what I came up with, which is a similar approach to Jayson:

    inline fun  MutableList.mutate(transform: (T) -> T): MutableList {
        return mutateIndexed { _, t -> transform(t) }
    }
    
    inline fun  MutableList.mutateIndexed(transform: (Int, T) -> T): MutableList {
        val iterator = listIterator()
        var i = 0
        while (iterator.hasNext()) {
            iterator.set(transform(i++, iterator.next()))
        }
        return this
    }
    

提交回复
热议问题