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

相关方法

相关推荐
alexhilton29 分钟前
务实的模块化:连接模块(wiring modules)的妙用
android·kotlin·android jetpack
ji_shuke1 小时前
opencv-mobile 和 ncnn-android 环境配置
android·前端·javascript·人工智能·opencv
sunnyday04263 小时前
Spring Boot 项目中使用 Dynamic Datasource 实现多数据源管理
android·spring boot·后端
幽络源小助理4 小时前
下载安装AndroidStudio配置Gradle运行第一个kotlin程序
android·开发语言·kotlin
inBuilder低代码平台4 小时前
浅谈安卓Webview从初级到高级应用
android·java·webview
豌豆学姐5 小时前
Sora2 短剧视频创作中如何保持人物一致性?角色创建接口教程
android·java·aigc·php·音视频·uniapp
白熊小北极5 小时前
Android Jetpack Compose折叠屏感知与适配
android
HelloBan5 小时前
setHintTextColor不生效
android
洞窝技术7 小时前
从0到30+:智能家居配网协议融合的实战与思考
android