I want to know actually how .indices works and what is the main difference is between this two for loops.
for (arg in args)
println(arg)
or
for (i in args.indices)
println(args[i])
And what is use of withIndex()
function
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
These are just different ways to iterate over an array, depending on what you need access to within the body of the for
loop: the current element (first case), the current index (second case), or both (third case).
If you're wondering about how they work under the hood, you can just jump into the code of the Kotlin runtime (Ctrl+B in IntelliJ), and find out.
For indices
specifically, this is pretty simple, it's implemented as an extension property that returns an IntRange
which a for
loop can then iterate over:
/**
* Returns the range of valid indices for the array.
*/
public val <T> Array<out T>.indices: IntRange
get() = IntRange(0, lastIndex)
As mentioned in the documentation indices is the index value from the list.
Returns an IntRange of the valid indices for this collection.
For more details refer to the documentation
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