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

相关方法

相关推荐
00后程序员张1 天前
从审核被拒到稳定过审,iOS 上架技术优化
android·ios·小程序·https·uni-app·iphone·webview
不会写DN1 天前
PHP 中的文件读写与上传
android·开发语言·php
冬奇Lab1 天前
Android 15音频子系统(七):音量控制系统深度解析
android·音视频开发
方白羽2 天前
Android NFC 功能集成-读卡器模式
android·app·客户端
进击的cc2 天前
Android Kotlin:委托属性深度解析
android·kotlin
进击的cc2 天前
Android Kotlin:Kotlin数据类与密封类
android·kotlin
恋猫de小郭2 天前
你的蓝牙设备可能正在泄漏你的隐私? Bluehood 如何追踪附近设备并做隐私分析
android·前端·ios
私人珍藏库2 天前
[Android] 卫星地图 共生地球 v1.1.22
android·app·工具·软件·多功能
冰珊孤雪2 天前
Android Studio Panda革命性升级:内存诊断、构建标准化与AI调试全解析
android·前端
_李小白2 天前
【OSG学习笔记】Day 23: ClipNode(动态裁剪)
android·笔记·学习