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

相关方法

相关推荐
plainGeekDev18 分钟前
Android 专家岗 Kotlin 面试题:能答出这些,说明你对语言设计有自己的理解
android·kotlin
plainGeekDev23 分钟前
Android 资深岗 Kotlin 面试题:只会用协程不够,你得懂它为什么这么设计
android·kotlin
StarShip35 分钟前
第一阶段:应用层视图绘制
android
StarShip37 分钟前
第二阶段:RenderThread 渲染处理
android
通玄1 小时前
Jetpack Compose 入门系列(一):从零搭建到基础控件使用
android
StarShip1 小时前
Android 图形渲染流水线完整架构与执行流程分析
android
流年如夢1 小时前
类和对象(上)
android·java·开发语言
用户86022504674722 小时前
从入门到进阶的 React Native 实战指南
android·前端
沐言人生2 小时前
ReactNative 源码分析10——Native View创建流程createView
android·react native