本文方法及代码示例基于Kotlin 2.1.20 Released
getOrPut
所在包 kotlin.collections.getOrPut
,其相关用法介绍如下:
用法:
kotlin
inline fun <K, V> MutableMap<K, V>.getOrPut(
key: K,
defaultValue: () -> V
): V
返回给定键的值。如果在映射中找不到键,则调用defaultValue 函数,将其结果放入映射中给定键下并返回。
请注意,如果同时修改映射,则不能保证操作是原子的。
代码示例:
kotlin
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
}
// 输出
2
2
null
42
相关方法
- Kotlin contentToString用法及代码示例
- Kotlin dropWhile用法及代码示例
- Kotlin distinct用法及代码示例
- Kotlin code用法及代码示例
- Kotlin Map:mapOf()用法及代码示例
- Kotlin distinctBy用法及代码示例
- Kotlin digitToChar用法及代码示例
- Kotlin ifBlank用法及代码示例
- Kotlin all用法及代码示例
- Kotlin digitToIntOrNull用法及代码示例
- Kotlin dropLast用法及代码示例
- Kotlin dropLastWhile用法及代码示例
- Kotlin associateBy用法及代码示例
- Kotlin groupingBy用法及代码示例
- Kotlin groupBy用法及代码示例
- Kotlin getOrElse用法及代码示例