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

相关方法

相关推荐
QuantumLeap丶38 分钟前
《Flutter全栈开发实战指南:从零到高级》- 12 -状态管理Bloc
android·flutter·ios
fatiaozhang95271 小时前
晶晨S905X芯片_通刷固件包_ATV 安卓9.0_IPV6_中文线刷固件包
android·电视盒子·刷机固件·机顶盒刷机固件
下位子3 小时前
『OpenGL学习滤镜相机』- Day5: 纹理变换与矩阵操作
android·opengl
撩得Android一次心动3 小时前
Android 四大组件——BroadcastReceiver(广播)
android·java·android 四大组件
努力学习的小廉3 小时前
初识MYSQL —— 复合查询
android·数据库·mysql
ii_best4 小时前
安卓/IOS工具开发基础教程:按键精灵一个简单的文字识别游戏验证
android·开发语言·游戏·ios·编辑器
Digitally13 小时前
如何用5种实用方法将电脑上的音乐传输到安卓手机
android·智能手机·电脑
HahaGiver66614 小时前
Unity与Android原生交互开发入门篇 - 打开Unity游戏的设置
android·unity·交互
2501_9159090614 小时前
WebView 调试工具全解析,解决“看不见的移动端问题”
android·ios·小程序·https·uni-app·iphone·webview
IT乐手15 小时前
android 下载管理工具类
android