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

相关方法

相关推荐
雨白3 小时前
掌握 NestedScrolling 嵌套滑动:手写仿知乎折叠主页
android
Xzaveir5 小时前
别把所有“认证”都塞进 AuthService:实名、一键登录与号码身份的领域拆分
android·人工智能
BerrySen1785 小时前
KMP全栈开发:从Android到AI Agent的技术演进与实践
android·人工智能
AFinalStone6 小时前
Android 7系统休眠唤醒(一)电源管理架构全景图
android·powermanager·电源管理
YM52e7 小时前
鸿蒙Flutter Center居中组件:Align对齐详解
android·学习·flutter·华为·harmonyos·鸿蒙
时间的拾荒人7 小时前
MySQL 视图详解
android·数据库·mysql
祉猷并茂,雯华若锦8 小时前
Appium 3.x安卓按键与通知栏操作全指南
android·appium
码农coding9 小时前
android 12 SurfaceFlinger开机启动分析
android
hunterandroid9 小时前
Paging 3 RemoteMediator 实战:构建离线优先的分页列表
android·前端
码农coding9 小时前
android12 开机启动PMS
android