Kotlin map()

Kotlin map()

In Kotlin, the map() function is used to transform each element of a collection using a specified transformation function. It returns a new collection with the transformed elements.

This function is commonly used when you want to apply a certain operation to each element of a collection and create a new collection with the results.

In this tutorial, we’ll explore the syntax of the map() function and provide examples of its usage in Kotlin.

Syntax

The syntax of the map() function is:

inline fun <T, R> Iterable<T>.map(
    transform: (T) -> R
): List<R>

The map() function takes a transformation function as an argument, and it applies this function to each element of the original collection, producing a new collection of the transformed elements.

Examples for map() function

1. Using map() to Square Each Element

In this example, we’ll use map() to square each element of a list of integers.

Kotlin Program

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)
    
    // Using map to square each element
    val squaredNumbers = numbers.map { it * it }
    
    // Printing the original and transformed lists
    println("Original list: ${numbers.joinToString(", ")}")
    println("Squared list: ${squaredNumbers.joinToString(", ")}")
}

Output

Original list: 1, 2, 3, 4, 5
Squared list: 1, 4, 9, 16, 25

In this example, the map() function is used to square each element of the original list of integers. The original and transformed lists are then printed to the console.

Summary

In this tutorial, we’ve covered the map() function in Kotlin, its syntax, and how to use it for transforming each element of a collection using a specified transformation function.