Kotlin Array.mapIndexed()

Kotlin Array.mapIndexed() Tutorial

The Array.mapIndexed() function in Kotlin is used to transform the elements of an array by applying a given transformation function to each element along with its index. It returns a new list containing the transformed elements.

This tutorial will explore the syntax of the Array.mapIndexed() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.mapIndexed() function is as follows:

fun <T, R> Array<out T>.mapIndexed(
    transform: (index: Int, T) -> R
): List<R>

where

ParameterDescription
transformFunction that takes the index and element as arguments and returns the transformed value.
Parameters of Array.mapIndexed()

Examples for Array mapIndexed() function

1. Transform an Array of integers using mapIndexed()

In this example, we’ll use the mapIndexed() function to transform an array of numbers by adding their index to each element.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(10, 20, 30, 40, 50)

    // Using mapIndexed() to add index to each element in the array
    val indexedSum = numbersArray.mapIndexed { index, value -> index + value }

    // Printing the original array and the result
    println("Numbers Array:\n${numbersArray.joinToString(", ")}\n")
    println("Indexed Sum:\n${indexedSum.joinToString(", ")}")
}

Output

Numbers Array:
10, 20, 30, 40, 50

Indexed Sum:
10, 21, 32, 43, 54

Explanation

Value + Index  = Element in Returned List
10    + 0      = 10
20    + 1      = 21
30    + 2      = 32
40    + 3      = 43
50    + 4      = 54

Summary

In this tutorial, we’ve covered the mapIndexed() function in Kotlin arrays, its syntax, and how to use it to transform array elements along with their indices. This function is useful for performing transformations that depend on both the element value and its position in the array.