Kotlin getOrPut用法及代码示例

本文方法及代码示例基于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

相关方法

相关推荐
zhangphil4 分钟前
Android宽高不均等Bitmap缩放为指定宽高FitCenter到正方形Bitmap,Kotlin
android·kotlin
别或许31 分钟前
13.用户管理
android
q***96582 小时前
springboot3整合knife4j详细版,包会!(不带swagger2玩)
android·前端·后端
巧克力芋泥包6 小时前
前端使用阿里云图形验证码;并且与安卓进行交互
android·前端·阿里云
Just_Paranoid9 小时前
【MQTT】基于 Android 设备接入物联网平台最佳实践
android·mqtt·eclipse·iot·paho·mqtt.fx
alexhilton12 小时前
深入理解withContext和launch的真正区别
android·kotlin·android jetpack
TDengine (老段)15 小时前
TDengine 转换函数 TO_JSON 用户手册
android·大数据·数据库·json·时序数据库·tdengine·涛思数据
q***428216 小时前
SpringCloudGateWay
android·前端·后端
卫生纸不够用16 小时前
Appium-锁屏-Android
android·appium
阿拉斯攀登16 小时前
安卓工控机 OTA 升级方案(SpringBoot+MQTT)
android·spring boot·物联网·iot