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

相关方法

相关推荐
青莲8438 分钟前
深拷贝 vs 浅拷贝
android
一枚小小程序员哈21 分钟前
基于Android的音乐播放器/基于android studio的音乐系统/音乐管理系统
android·ide·android studio
叽哥1 小时前
flutter学习第 13 节:本地存储
android·flutter·ios
whysqwhw5 小时前
安卓上WebRtc
android
青莲8435 小时前
内联函数 inline noinline crossinline reified
android
wayne2145 小时前
从 MVC 到 MVI:Android 架构演进全景剖析与示例代码
android
我又来搬代码了7 小时前
【Android】【bug】Json解析错误Expected BEGIN_OBJECT but was STRING...
android·json·bug
CANI_PLUS16 小时前
ESP32将DHT11温湿度传感器采集的数据上传到XAMPP的MySQL数据库
android·数据库·mysql
来来走走17 小时前
Flutter SharedPreferences存储数据基本使用
android·flutter
安卓开发者19 小时前
Android模块化架构深度解析:从设计到实践
android·架构