Sobes.tech
Junior — Middle

How does the map function in Kotlin differ from similar methods and how is it used to transform collection elements?

sobes.tech AI

Answer from AI

The map function in Kotlin is used to transform elements of a collection by applying a given function to each element and returning a new collection with the results. This is a functional approach to data processing that allows for easy and concise modification of collection contents.

Differences of map in Kotlin from similar methods in other languages:

  • map returns a new collection of the same type (e.g., List) without modifying the original.
  • Supports lambda expressions, making the code compact and readable.

Example of usage:

val numbers = listOf(1, 2, 3, 4)
val squares = numbers.map { it * it }
println(squares) // Outputs: [1, 4, 9, 16]

Here, each element of the numbers list is squared, and the result is stored in a new list squares.

Thus, map is a convenient tool for transforming collections without altering the original data.