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

用法:

inline fun <T, K, V, M : MutableMap<in K, in V>> Sequence<T>.associateTo(
    destination: M, 
    transform: (T) -> Pair<K, V>
): M

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

如果两对中的任何一对具有相同的 key ,则最后一个将添加到Map中。

操作是 terminal

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
data class Person(val firstName: String, val lastName: String)

val scientists = listOf(Person("Grace", "Hopper"), Person("Jacob", "Bernoulli"), Person("Johann", "Bernoulli"))

val byLastName = mutableMapOf<String, String>()
println("byLastName.isEmpty() is ${byLastName.isEmpty()}") // true

scientists.associateTo(byLastName) { it.lastName to it.firstName }

println("byLastName.isNotEmpty() is ${byLastName.isNotEmpty()}") // true
// Jacob Bernoulli does not occur in the map because only the last pair with the same key gets added
println(byLastName) // {Hopper=Grace, Bernoulli=Johann}
//sampleEnd
}

输出:

byLastName.isEmpty() is true
byLastName.isNotEmpty() is true
{Hopper=Grace, Bernoulli=Johann}