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

相关方法

相关推荐
董三毛2 小时前
Kotlin Coroutine 底层实现原理
android
L108702 小时前
AutoJsPro GoogleMaterial3 M3组件使用示例
android
枣把儿4 小时前
「zotepad」用Gemini3pro写出一个高效写作和发文的记事本应用
android·前端·nuxt.js
明川4 小时前
Android Gradle 学习 - 生命周期和Task
android·前端·gradle
技术摆渡人4 小时前
Android 系统技术探索(5)指尖的舞蹈(Input 系统与 ANR)
android
来碗疙瘩汤4 小时前
uniapp动态读取版本号
android
用户41659673693555 小时前
存量项目如何拥抱 KMP?从环境搭建到组件化集成的保姆级指南
android
技术摆渡人6 小时前
Android 系统技术探索(3)光影魔术(SurfaceFlinger & 图形栈)。
android
某空m6 小时前
【Android】浅析DataBinding
android·开发语言
sky北城7 小时前
You are not able to choose some of the languages, because locales for them a
android