Collection processing in Kotlin: Using indices
Sometimes we are not only interested in elements but also in their positions in a collection. Let's say that in one of your collection processing functions you need to depend not only on an element’s value but also on its index in the collection. The generic way is to use the
withIndex function, which lazily transforms a list of elements into a list of indexed elements. These elements can be then destructured1 into an index and a value.
This is a universal iterator function, but many collection processing functions do not need it because they have "indexed" variants. For instance, there are the
scanIndexed functions, which work the same as
scan, but they also have an index in the first position of their operation.
Notice that using
withIndex adds the current index to each element, and this index stays the same for all steps, while the indexed function operates on the current index for each step.
Destructuring is creating multiple variables based on a single value. This concept is explained in the book Kotlin Essentials.