Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Difference between "forEachIndexed" and "for in" loop

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?

like image 945
Bitcoin Cash - ADA enthusiast Avatar asked Sep 19 '17 23:09

Bitcoin Cash - ADA enthusiast


People also ask

What is forEachIndexed in Kotlin?

Performs the given action on each element, providing sequential index with the element.

How do you break a forEach loop in Kotlin?

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.

How do I get position in forEach Kotlin?

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.


1 Answers

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.

like image 109
Joshua Avatar answered Oct 23 '22 04:10

Joshua