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

相关方法

相关推荐
GitLqr1 小时前
Flutter FocusNode 实战指南:玩转键盘焦点与用户输入体验
android·flutter·ios
酷在前行2 小时前
【R绘图】Nature Communications 半眼图复刻:分布、区间与多面板排版(保姆级教程)
android·开发语言·r语言
2501_932750263 小时前
Android registerForActivityResult 详解
android
小孔龙5 小时前
VSync 与同步屏障:doFrame() 的优先调度
android·性能优化
kfzjw0085 小时前
Android 的一帧完整渲染流程:从 VSYNC 到 Screen 的全链路解密
android
wWYy.6 小时前
Mysql:覆盖索引
android·数据库·mysql
Kapaseker6 小时前
如果我要从 List 中获取一段元素
android·kotlin
三少爷的鞋6 小时前
一次朋友圈发布流程,理解 Kotlin 协程为什么重新定义异步代码组织方式
android
FungLeo7 小时前
Flutter/Android Release 包连不上网?AndroidManifest INTERNET 权限排查实录
android·flutter
wWYy.9 小时前
Mysql:一行数据是怎么存储的?
android·数据库·mysql