🐦 Kotlin Intermediate

What does flatMap do in Kotlin?

Answer

flatMap transforms each element into a collection and then flattens all resulting collections into a single list. It is equivalent to calling .map { }.flatten() in one step. Example: val allTags = posts.flatMap { it.tags } — if each post has a list of tags, flatMap gives you one flat list of all tags from all posts. This is one of the most useful collection functions for working with nested structures. Use it whenever your map function returns a List and you want a flat result instead of a list of lists.