Sometimes, we want to associate a collection of values with some other values. One way to accomplish this is by making use of the associate() function. With associate(), we can map each value of a collection to a pair of any desired type and then save the resulting map.
In this example, we'll map each string to its length and then iterate over every pair in the map, printing them out as we go:
list.associate { it to it.length }
.forEach {
println("${it.key} has ${it.value} letters")
}
Running this code will result in the following output:
Kotlin has 6 letters
Java has 4 letters
Swift has 5 letters
K has 1 letters
The associate() function greatly simplifies the work required to create a map of associated values based on an input collection.