Kotlin - “forEachIndexed”和“for in”循环之间的区别

Tia*_*ago 8 foreach for-loop kotlin

我对每种方法的优点/缺点感到困惑(假设我需要同时使用indexproduct):

products.forEachIndexed{ index, product ->
    ...
}

for ((index, product) in products.withIndex()) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

products 这是一个简单的集合。

是否有任何性能/最佳实践/等论据来选择一个而不是另一个?

Jos*_*hua 9

不,它们是一样的。您可以阅读forEachIndexedwithIndex的来源。

public inline fun <T> Iterable<T>.forEachIndexed(action: (index: Int, T) -> Unit): Unit {
    var index = 0
    for (item in this) action(index++, item)
}


public fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>> {
    return IndexingIterable { iterator() }
}
Run Code Online (Sandbox Code Playgroud)

forEachIndexed使用本地 var 来计算索引,同时withIndex为迭代器创建一个装饰器,它也使用 var 来计算索引。理论上,再withIndex创建一层包装,但性能应该是相同的。