🐦 Kotlin Intermediate

What does the map function do in Kotlin collections?

Answer

The map function transforms each element of a collection using a provided function and returns a new list of the same size. val names = users.map { it.name } returns a List<String> from a List<User>. Every element is transformed — the result always has the same number of elements as the original. Related variants: mapNotNull { } transforms and filters out null results in one pass, mapIndexed { index, element -> } provides access to the element's position, and flatMap { } for when the transform returns a list that should be flattened.