Kotlin List onEachIndexed()
Syntax & Examples


Syntax of List.onEachIndexed()

The syntax of List.onEachIndexed() extension function is:

fun <T, C : Iterable<T>> C.onEachIndexed( action: (index: Int, T) -> Unit ): C

This onEachIndexed() extension function of List performs the given action on each element, providing sequential index with the element, and returns the collection itself afterwards.



✐ Examples

1 Example

In this example,

  • We create a list of integers named list containing elements 1, 2, 3, 4, 5.
  • We use the onEachIndexed() function to perform an action on each element with its index.
  • The action prints each element along with its index to standard output.
  • As a result, we get the output showing each element with its index.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5)
    list.onEachIndexed { index, element -> println("Element $element at index $index") }
}

Output

Element 1 at index 0
Element 2 at index 1
Element 3 at index 2
Element 4 at index 3
Element 5 at index 4

2 Example

In this example,

  • We create a list of characters named list containing elements 'a', 'e', 'i', 'o', 'u'.
  • We use the onEachIndexed() function to perform an action on each element with its index.
  • The action prints each vowel along with its index to standard output.
  • As a result, we get the output showing each vowel with its index.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'e', 'i', 'o', 'u')
    list.onEachIndexed { index, element -> println("Vowel $element at index $index") }
}

Output

Vowel a at index 0
Vowel e at index 1
Vowel i at index 2
Vowel o at index 3
Vowel u at index 4

3 Example

In this example,

  • We create a list of strings named list containing elements "apple", "banana", "cherry".
  • We use the onEachIndexed() function to perform an action on each element with its index.
  • The action prints each fruit along with its index to standard output.
  • As a result, we get the output showing each fruit with its index.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry")
    list.onEachIndexed { index, element -> println("Fruit $element at index $index") }
}

Output

Fruit apple at index 0
Fruit banana at index 1
Fruit cherry at index 2

Summary

In this Kotlin tutorial, we learned about onEachIndexed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.