inline fun <K, V> MutableMap<K, V>.getOrPut( key: K, defaultValue: () -> V ): V
Returns the value for the given key. If the key is not found in the map, calls the defaultValue function, puts its result into the map under the given key and returns it.
import kotlin.test.*
import java.util.*
import kotlin.comparisons.*
fun main(args: Array<String>) {
//sampleStart
val map = mutableMapOf<String, Int?>()
println(map.getOrPut("x") { 2 }) // 2
println(map.getOrPut("x") { 3 }) // 2 // still
println(map.getOrPut("y") { null }) // null
println(map.getOrPut("y") { 42 }) // 42 // but!
//sampleEnd
}
© 2010–2017 JetBrains s.r.o.
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/get-or-put.html