...

/

Higher-Order Functions on Collections

Higher-Order Functions on Collections

Learn how to apply higher-order functions on collections in Kotlin.

Mapping elements

The map() function takes each element of a collection and returns a new element of a possibly different type. To understand this idea better, let’s say we have a list of letters and we would like to output their ASCII values.

First, let’s implement it in an imperative way:

val letters = 'a'..'z'
val ascii = mutableListOf<Int>()
for (l in letters) {
ascii.add(l.toInt())
}
Generating a list of ASCII values for lowercase letters a to z

Notice that even for such a trivial task, we had to write quite a lot of code. We also had to define our output list as mutable.

Now, the same code using the map() function would look like this:

val result: List<Int> = ('a'..'z').map { it.toInt() }

Notice how much shorter the implementation is. We don’t need to define a mutable list, nor do we need to write a for loop ourselves. See the output by running the code below:

Note: The function toInt() is deprecated so it gives warnings. We have used it here for the sake of understanding.

Press + to interact
fun main() {
val letters = 'a'..'z'
val ascii = mutableListOf<Int>()
for (l in letters) {
ascii.add(l.toInt())
}
println(ascii)
val result: List<Int> = ('a'..'z').map { it.toInt() }
println(result)
}

Filtering elements

Another common task is filtering a collection. We know the drill—we iterate over it and only put values that fit our criteria in a new collection. For example, if ...