What does meaning mean in Kotlin?

I want to know how .indices works and what is the main difference between these two loops.

for (arg in args)
    println(arg)

      

or

for (i in args.indices)
    println(args[i])

      

And what is function withIndex()

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

      

+3


source to share


2 answers


They are just different ways to iterate over the array, depending on what you want to get inside the body of the loop for

: the current element (first case), the current index (second case), or both (third case).

If you're wondering how they work under the hood, you can just jump into the Kotlin runtime code ( Ctrl+ Bin IntelliJ) and find out.



For indices

in particular, it's pretty simple, it's implemented as an extension property that returns IntRange

, which can then loop for

:

/**
 * Returns the range of valid indices for the array.
 */
public val <T> Array<out T>.indices: IntRange
    get() = IntRange(0, lastIndex)

      

+4


source


As stated in the documentation, indices are an index value from a list.

Returns an IntRange of valid indices for this collection.



See documentation for details

+2


source







All Articles