Rohit Parmar
Rohit Parmar

Reputation: 397

What is .indices meaning in 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")
}

Upvotes: 15

Views: 12697

Answers (4)

kirkadev
kirkadev

Reputation: 348

When I wrote

for (i in 0..searchResultsTemp.items.size-1 )
        { " la-la-la "}, 

I wanted to work with each item of the collection, but I wouldn't use forEach operator, I would have access to the index of the collection item. Then the built-in Android Studio helper suggested to me to automatically replace this expression with

 for (i in searchResultsTemp.items.indices)
        { " la-la-la "}

It is the same.

Upvotes: 0

Suraj Vaishnav
Suraj Vaishnav

Reputation: 8305

indices returns IntRange(range of index from first to the last position) of collection, for example:

val array= arrayOf(10,20,30,40,50,60,70)

println("Indices: "+array.indices) // output: Indices: 0..6  

In the question, both the loop are doing the same thing and just different way of iterate any collection(as @zsmb13 mentioned) but, the 2nd for loop does not create an iterator object as the first one does.

indices returns IntRange so you must check these useful methods of IntRange

Upvotes: 1

zsmb13
zsmb13

Reputation: 89548

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)

Upvotes: 12

Rahul Khurana
Rahul Khurana

Reputation: 8834

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

Upvotes: 2

Related Questions