The map() function
One of the most well known higher-order functions on collections is map()
.
Let's say you have a function that receives a list of strings and returns a new list of the same size containing each string concatenated to itself:
val letters = listOf("a", "b", "c", "d") println(repeatAll(letters)) // [aa, bb, cc, dd]
The task is quite trivial:
fun repeatAll(letters: List<String>): MutableList<String> { val repeatedLetters = mutableListOf<String>() for (l in letters) { repeatedLetters.add(l + l) } return repeatedLetters }
But for such a trivial task, we had to write quite a lot of code. What would we have to change in order to capitalize each string instead of repeating it twice? We would like to change only this line:
repeatedLetters.add(l + l) ----> repeatedLetters.add(l.toUpperCase())
But we have to create another function for that.
Of course, in Kotlin, we could pass a function as a second parameter. And since we don't actually care what the type...