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

相关方法

相关推荐
好的佩奇8 小时前
Dart 之可迭代对象与生成器
android·flutter·dart
_祝你今天愉快8 小时前
Paint Cavans高级绘制:[三] Canvas高阶使用技巧-变换,状态保存,离屏缓冲,粒子特效
android
小乖写代码8 小时前
提交注册验证 · WhatsApp /v2/register
android·网络·账号注册
二流小码农13 小时前
鸿蒙开发:router组件升级,彻底告别手动配置
android·ios·harmonyos
Digitally13 小时前
如何在安卓设备上使用 4 种简单方法将应用移动到 SD 卡
android
booboosui15 小时前
录一遍就会:8 种步骤、6 类失败,卡住时只修那一步
android
阿杰m15 小时前
Android源码第十五章:Camera2 与 CameraService——一帧图像怎样回到应用
android
恋猫de小郭21 小时前
Flutter Analyzer 系列坑推进,必看,AI 时代这玩意最吃你内存
android·前端·flutter
LinXunFeng1 天前
拿竞品 App 一扫,技术栈全暴露了
android·flutter·开源
Gracker1 天前
AIW:从系统机制到性能排查,一本可以对照源码的 Android 电子书
android