associateWithTo所在位置是kotlin.sequences.associateWithTo,其相关用法介绍如下。

用法:

inline fun <K, V, M : MutableMap<in K, in V>> Sequence<K>.associateWithTo(
    destination: M, 
    valueSelector: (K) -> V
): M

使用给定序列的每个元素的键值对填充并返回 destination 可变映射,其中键是元素本身,值由应用于该键的 valueSelector 函数提供。

如果任何两个元素相等,则最后一个元素将覆盖映射中的前一个值。

操作是 terminal

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
data class Person(val firstName: String, val lastName: String) {
    override fun toString(): String = "$firstName $lastName"
}

val scientists = listOf(Person("Grace", "Hopper"), Person("Jacob", "Bernoulli"), Person("Jacob", "Bernoulli"))
val withLengthOfNames = mutableMapOf<Person, Int>()
println("withLengthOfNames.isEmpty() is ${withLengthOfNames.isEmpty()}") // true

scientists.associateWithTo(withLengthOfNames) { it.firstName.length + it.lastName.length }

println("withLengthOfNames.isNotEmpty() is ${withLengthOfNames.isNotEmpty()}") // true
// Jacob Bernoulli only occurs once in the map because only the last pair with the same key gets added
println(withLengthOfNames) // {Grace Hopper=11, Jacob Bernoulli=14}
//sampleEnd
}

输出:

withLengthOfNames.isEmpty() is true
withLengthOfNames.isNotEmpty() is true
{Grace Hopper=11, Jacob Bernoulli=14}