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

相关方法

相关推荐
StarShip9 小时前
SystemServer类 与 system_server进程
android
画个太阳作晴天10 小时前
Android App 跟随系统自动切换白天/黑夜模式:车机项目实战经验分享
android·android studo
成都大菠萝10 小时前
2-2-2 快速掌握Kotlin-语言的接口默认实现
android
代码s贝多芬的音符10 小时前
android webview 打开相机 相册 图片上传。
android·webview·webview打开相机相册
游戏开发爱好者811 小时前
抓包工具有哪些?代理抓包、数据流抓包、拦截转发工具
android·ios·小程序·https·uni-app·iphone·webview
StarShip11 小时前
Android system_server进程介绍
android
StarShip11 小时前
Android Context 的 “上下文”
android
成都大菠萝11 小时前
2-6-1 快速掌握Kotlin-语言的接口定义
android
李小轰_Rex11 小时前
纯算法AEC:播录并行场景的回声消除实战笔记
android·音视频开发
ok406lhq12 小时前
unity游戏调用SDK支付返回游戏会出现画面移位的问题
android·游戏·unity·游戏引擎·sdk