The associateWithTo() extension function for sets in Kotlin populates and returns the destination mutable map with key-value pairs for each element of the set, where the key is the element itself and the value is provided by the valueSelector function applied to that key.
The syntax of Set.associateWithTo() extension function is:
fun <K, V, M : MutableMap<in K, in V>> Set<K>.associateWithTo(destination: M, valueSelector: (K) -> V): M
This associateWithTo() extension function of Set populates and returns the destination mutable map with key-value pairs for each element of the given set, where the key is the element itself and the value is provided by the valueSelector function applied to that key.
Parameter | Optional/Required | Description |
---|---|---|
destination | required | The mutable map to which key-value pairs will be added. |
valueSelector | required | A function that takes an element of the set and returns a value for the resulting map. |
Set.associateWithTo() returns value of type M
.
In Kotlin, we can use the associateWithTo()
function to populate a mutable map with elements from a set of strings, where the keys are the strings and the values are their lengths.
For example,
associateWithTo()
function with a valueSelector function that returns the length of the string.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry")
val fruitLengths = mutableMapOf<String, Int>()
fruits.associateWithTo(fruitLengths) { it.length }
println("Fruit lengths: $fruitLengths")
}
Fruit lengths: {apple=5, banana=6, cherry=6}
In Kotlin, we can use the associateWithTo()
function to populate a mutable map with elements from a set of integers, where the keys are the integers and the values are their squares.
For example,
associateWithTo()
function with a valueSelector function that returns the square of the integer.println
function.fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5)
val squaresMap = mutableMapOf<Int, Int>()
numbers.associateWithTo(squaresMap) { it * it }
println("Number squares: $squaresMap")
}
Number squares: {1=1, 2=4, 3=9, 4=16, 5=25}
In Kotlin, we can use the associateWithTo()
function to populate a mutable map with elements from an empty set, which will result in an empty map.
For example,
associateWithTo()
function with a valueSelector function that returns the square of the integer.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val squaresMap = mutableMapOf<Int, Int>()
emptySet.associateWithTo(squaresMap) { it * it }
println("Number squares in empty set: $squaresMap")
}
Number squares in empty set: {}
In this Kotlin tutorial, we learned about associateWithTo() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.