getOrPut
Требования к платформе и версии: JVM (1.0), JS (1.0), Native (1.0)
inline fun <K, V> MutableMap<K, V>.getOrPut( key: K, defaultValue: () -> V ): V
Возвращает значение для заданного ключа. Если ключ не найден в карте, вызывает функцию defaultValue, помещает её результат в карту по заданному ключу и возвращает его.
Обратите внимание, что операция не гарантируется как атомарная, если карта изменяется одновременно.
import kotlin.test.*
import java.util.*
fun main(args: Array<String>) {
//sampleStart
val map = mutableMapOf<String, Int?>()
println(map.getOrPut("x") { 2 }) // 2
// subsequent calls to getOrPut do not evaluate the default value
// since the first getOrPut has already stored value 2 in the map
println(map.getOrPut("x") { 3 }) // 2
// however null value mapped to a key is treated the same as the missing value
println(map.getOrPut("y") { null }) // null
// so in that case the default value is evaluated
println(map.getOrPut("y") { 42 }) // 42
//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.collections/get-or-put.html