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

我很困惑这些方法的优点和缺点(假设我需要使用indexproduct ):

 products.forEachIndexed{ index, product -> ... } for ((index, product) in products.withIndex()) { ... } 

这里的products是一个简单的集合。

是否有任何表现/最佳实践/等论点比较喜欢一个?

不,他们是一样的。 您可以阅读forEachIndexed和withIndex的来源。

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

forEachIndexed使用本地var来计数索引,而withIndex为迭代器创建一个装饰器,它也使用var来计数索引。 从理论上讲,用withIndex创建一个包装层,但性能应该是一样的。