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

相关方法

相关推荐
Try02144 分钟前
Kotlin中Lambda表达式妙用:超越基础语法的力量
kotlin
whysqwhw1 小时前
OkHttp深度架构缺陷分析与演进规划
android
用户7093722538511 小时前
Android14 SystemUI NotificationShadeWindowView 加载显示过程
android
木叶丸1 小时前
跨平台方案该如何选择?
android·前端·ios
顾林海2 小时前
Android ClassLoader加载机制详解
android·面试·源码
用户2018792831672 小时前
🎨 童话:Android画布王国的奇妙冒险
android
whysqwhw3 小时前
OkHttp框架的全面深入架构分析
android
你过来啊你3 小时前
Android App冷启动流程详解
android
泓博3 小时前
KMP(Kotlin Multiplatform)改造(Android/iOS)老项目
android·ios·kotlin
移动开发者1号4 小时前
使用Baseline Profile提升Android应用启动速度的终极指南
android·kotlin