W3cubDocs

/Kotlin

associateTo

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <K, V, M : MutableMap<in K, in V>> CharSequence.associateTo(
    destination: M, 
    transform: (Char) -> Pair<K, V>
): M

Populates and returns the destination mutable map with key-value pairs provided by transform function applied to each character of the given char sequence.

If any of two pairs would have the same key the last one gets added to the map.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val string = "bonne journée"
// associate each character with its code
val result = mutableMapOf<Char, Int>()
string.associateTo(result) { char -> char to char.toInt() }
// notice each letter occurs only once
println(result) // {b=98, o=111, n=110, e=101,  =32, j=106, u=117, r=114, é=233}
//sampleEnd
}

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/associate-to.html