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

相关方法

相关推荐
YXL1111YXL32 分钟前
LeakCanary 源码解析检测泄露工作机制(一)
android·leakcanary
且随疾风前行.2 小时前
Android Binder 驱动 - 内核驱动层源码初探
android·网络·binder
额恩663 小时前
AI 智能体从零搭建实战教程——扣子
android·rxjava·coze
帅次3 小时前
Kotlin Flow 与 StateFlow:UI 单向数据流基础
开发语言·ui·kotlin·stateflow·onlifecycle
hunterandroid3 小时前
前台服务适配与线上排查:通知权限、启动限制和任务保活
android·前端
帅次3 小时前
Android 高级工程师面试:Flutter 渲染与性能 近1年高频追问 20 题
android·flutter·面试·渲染·性能
糖果店的幽灵4 小时前
【langgraph 从入门到精通graphApi 篇】Command 与动态流程控制
android·java·数据库·人工智能·langgraph
Android-Flutter5 小时前
Android的http和https知识点
android·http·https
Kapaseker5 小时前
Sequence 一定比 List 快?等等,我们先从基础讲起
android·kotlin
AI刀刀5 小时前
deepseek 内容粘贴后符号丢失怎么办?AI 导出鸭实测解决排版乱码问题
android·人工智能·excel·ai导出鸭