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

相关方法

相关推荐
2501_9159090629 分钟前
完整指南:如何将iOS应用上架到App Store
android·ios·小程序·https·uni-app·iphone·webview
赏金术士2 小时前
Retrofit + Kotlin 协程(Android 实战教程)
android·kotlin·retrofit
大炮筒9 小时前
COCOS2DX4.0CPPWIN移植安卓踩坑总结
android
qq_4228286212 小时前
android图形学之SurfaceControl和Surface的关系 五
android·开发语言·python
tongyiixiaohuang13 小时前
轻易云平台助力快麦数据入库MySQL
android·数据库·mysql
JohnnyDeng9416 小时前
Android 包体积优化:R8/ProGuard 深度配置
android
qq_4523962316 小时前
第六篇:《JMeter逻辑控制器:循环、条件和交替执行》
android·java·jmeter
高林雨露17 小时前
kotlin by 和 = 的区别在于【属性委托】和直【接赋值】的差异
kotlin
坐吃山猪17 小时前
【Hanako】README08_LEVEL4_插件系统架构
python·架构·agent·源码阅读
cwzqf18 小时前
Jectpack Compose项目组件代码分享(1):分页加载组件
android