Kotlin List – Get Indices

To get the indices range of a List in Kotlin, get the value of indices property for this List object.

The Kotlin List.indices property returns an IntRange object with valid indices for this list.

Syntax of List.indices

The syntax of List.indices property is

list.indices

Return Value

Returns an IntRange object of the valid indices for this list.

ADVERTISEMENT

Example 1: Get Indices Range of List

In this example, we will take a list of elements (of string type) and find the integer range of indices of this list.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd", "de", "ef", "fg", "gh")
    val indices = list1.indices
    print(indices)
}

Output

0..6

Let us print the indices by getting an iterator for the indexes in the indices IntRange object.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd", "de", "ef", "fg", "gh")
    val indices = list1.indices
    val indicesIterator = indices.iterator()
    while(indicesIterator.hasNext()) {
        println(indicesIterator.next())
    }
}

Output

0
1
2
3
4
5
6

Conclusion

In this Kotlin Tutorial, we learned how to the range of indices for the list, using Kotlin List.indices property.