Kotlin Array.map()

Kotlin Array.map() Tutorial

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

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

Syntax

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

fun <T, R> Array<out T>.map(transform: (T) -> R): List<R>

where

ParameterDescription
transformFunction that takes the element as argument and returns the transformed value.
Parameters of Array.map()

Examples for Array.map() function

1. Transform elements in given integer array to their squares

In this example, we’ll use the map() function to transform an array of numbers by squaring each element.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(1, 2, 3, 4, 5)

    // Using map() to square each element in the array
    val squaredNumbers = numbersArray.map { it * it }

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

Output

Numbers Array:
1, 2, 3, 4, 5

Squared Numbers:
1, 4, 9, 16, 25

2. Transform string array to a list of the respective string lengths

In this example, we’ll use the map() function to transform an array of string to a list containing lengths of the respective string elements.

Kotlin Program

fun main() {
    val wordsArray = arrayOf("apple", "fig", "banana")

    // Using map() to square each element in the array
    val wordLengths = wordsArray.map { it.length }

    // Printing the original array and the result
    println("Words Array:\n${wordsArray.joinToString(", ")}\n")
    println("Word Lengths:\n${wordLengths.joinToString(", ")}")
}

Output

Words Array:
apple, fig, banana

Word Lengths:
5, 3, 6

Summary

In this tutorial, we’ve covered the map() function in Kotlin arrays, its syntax, and how to use it to transform array elements. This function is useful for performing element-wise transformations on arrays, providing a concise and expressive way to modify array contents.