Collections 基于索引对列表项的不同函数调用

Collections 基于索引对列表项的不同函数调用,collections,kotlin,Collections,Kotlin,我有一份物品清单 val itemList = mutableListOf<Item>() 现在,我想迭代itemList并根据每个项的索引对其执行不同的操作,以避免IndexOutOfBoundsException 我知道它可以使用for与when组合来完成,但我想知道它是否可以在不使用whenforindex的情况下完成。 类似于将函数作为varargs传递,代码智能地对每个项执行操作 或者通过使用任何kotlin幂函数,如扩展函数或lambda函数,使用内置函数的解决方案:创

我有一份物品清单

val itemList = mutableListOf<Item>()
现在,我想迭代itemList并根据每个项的索引对其执行不同的操作,以避免IndexOutOfBoundsException

我知道它可以使用for与when组合来完成,但我想知道它是否可以在不使用whenforindex的情况下完成。 类似于将函数作为varargs传递,代码智能地对每个项执行操作


或者通过使用任何kotlin幂函数,如扩展函数或lambda函数,使用内置函数的解决方案:创建包含函数引用的函数列表:

val operations = listOf(::operation1, ::operation2, ::operation3, ::operation4, ::operation5)
然后将这些项与一个操作配对。
zip
方法的结果具有两个集合中较短集合的长度,以防它们的大小不匹配。然后您只需对这些项进行迭代,调用与每个项成对的操作(使用
forEach
函数的lambda参数的解构声明)


另一个具有您自己扩展功能的解决方案:

fun <T> List<T>.performOperations(vararg operations: (T) -> Unit) {
    this.forEachIndexed { index, item ->
        operations[index](item)
    }
}
请注意,这目前并不能很好地处理大小不匹配的问题,它需要为每个项目都提供一个函数。您可以将其更改为此表单,以便每个函数都需要一个项:

fun <T> List<T>.performOperations(vararg operations: (T) -> Unit) {
    operations.forEachIndexed { index, operation ->
        operation(this.get(index))
    }
}
fun List.性能操作(vararg操作:(T)->Unit){
operations.ForEachined{索引,操作->
操作(this.get(index))
}
}

函数引用的列表看起来确实是一个不错的选择。伟大的解决方案foreach拉链可完美解决尺寸不匹配问题
fun <T> List<T>.performOperations(vararg operations: (T) -> Unit) {
    this.forEachIndexed { index, item ->
        operations[index](item)
    }
}
itemList.performOperations(::operation1, ::operation2, ::operation3, ::operation4, ::operation5)
fun <T> List<T>.performOperations(vararg operations: (T) -> Unit) {
    operations.forEachIndexed { index, operation ->
        operation(this.get(index))
    }
}