October 2019
Intermediate to advanced
434 pages
11h 54m
English
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 lettersJava has 4 lettersSwift has 5 lettersK has 1 letters
The associate() function greatly simplifies the work required to create a map of associated values based on an input collection. ...
Read now
Unlock full access