Kotlin List.indices – Examples

Kotlin List.indices

The Kotlin List.indices property returns an IntRange of the valid indices for this list.

Syntax

List.indices

Example 1

In this example,

  1. Take a list of elements.
  2. Get the range of indices of this list using List.indices property.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c", "d", "e")
    val indices = list1.indices
    print(indices)
}

Output

0..4

Example 2

In this example,

  1. Take a list of strings.
  2. Get the indices of this list.
  3. Use these indices to access elements of the list.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c", "d", "e")
    val indices = list1.indices
    for (index in indices) {
        println(list1[index])
    }
}

Output

a
b
c
d
e