Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is .indices meaning in kotlin?

Tags:

kotlin

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")
}
like image 888
Rohit Parmar Avatar asked Jun 01 '17 09:06

Rohit Parmar


2 Answers

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)
like image 83
zsmb13 Avatar answered Oct 21 '22 03:10

zsmb13


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

like image 35
Rahul Khurana Avatar answered Oct 21 '22 03:10

Rahul Khurana