I am confused on what are the advantages/disadvantages of each of these approaches (assuming I need to use both index
and product
):
products.forEachIndexed{ index, product ->
...
}
for ((index, product) in products.withIndex()) {
...
}
products
here is a simple collection.
Is there any performance/best practice/etc argument to prefer one over the other?
Performs the given action on each element, providing sequential index with the element.
It's not possible to use the break and continue keywords to jump out of functional loops in Kotlin – at least, not in the traditional way. For example, we can't stop the execution of a forEach functional loop by simply writing the break statement. However, there are techniques we can use to mimic that behavior.
Example: Using forEachIndexed() nstead of using forEach() loop, you can use the forEachIndexed() loop in Kotlin. forEachIndexed is an inline function which takes an array as an input and its index and values are separately accessible.
No, they are the same. You can read the source of forEachIndexed and withIndex.
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() }
}
forEachIndexed
use a local var to count the index while withIndex
create a decorator for iterator which also use a var to count index. In theory, withIndex
create one more layer of wrapping but the performance should be the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With