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

相关方法

相关推荐
STCNXPARM5 小时前
Linux camera之V4L2子系统详解
android·linux·camera·v4l2架构
2501_944525545 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 账户详情页面
android·java·开发语言·前端·javascript·flutter
不急不躁1238 小时前
Android16 GTS GtsPermissionTestcases 测试,跳过权限检查
android
符哥200810 小时前
关于用Android Compose开发成不成熟的分析
android·android jetpack
蜗牛、Z10 小时前
Android 蓝牙/Wi-Fi通信协议之:蓝牙扫描ScanCallback详解
android
黄昏晓x10 小时前
Linux----进程控制
android·linux·运维
我是阿亮啊11 小时前
android中事件分发机制
android·事件分发·事件分发机制
心前阳光12 小时前
Unity 模拟父子关系
android·unity·游戏引擎
2501_9151063212 小时前
当 Perfdog 开始收费之后,我重新整理了一替代方案
android·ios·小程序·https·uni-app·iphone·webview
多多*12 小时前
2月3日面试题整理 字节跳动后端开发相关
android·java·开发语言·网络·jvm·adb·c#