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

相关方法

相关推荐
4z331 天前
Android15 Framework(1): 用户空间启动的第一个进程 Init
android·源码阅读
洛克希德马丁1 天前
Qt配置安卓开发环境
android·开发语言·qt
没有了遇见1 天前
Android 修改项目包名,一键解决.
android
Entropless1 天前
解剖OkHttp:那些主流教程未曾深入的设计精髓
android·okhttp
2501_915921431 天前
查看iOS App实时日志的正确方式,多工具协同打造高效调试与问题定位体系(2025最新指南)
android·ios·小程序·https·uni-app·iphone·webview
菠萝加点糖1 天前
Android 使用MediaMuxer+MediaCodec编码MP4视频异步方案
android·音视频·编码
cccccc语言我来了1 天前
深入理解 Linux(7) 命令与动态库:从文件操作到程序链接的实践指南
android·linux·运维
程序员卷卷狗1 天前
MySQL 慢查询优化:从定位、分析到索引调优的完整流程
android·mysql·adb
写点啥呢1 天前
Android Studio 多语言助手插件:让多语言管理变得简单高效
android·ai·ai编程·多语言
9527出列1 天前
Netty源码分析(终)--关于WriteAndFlush
netty·源码阅读