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

相关方法

相关推荐
2501_916008899 分钟前
移动应用上架到应用商店的完整指南:原理与详细步骤
android·ios·小程序·https·uni-app·iphone·webview
草莓熊Lotso10 分钟前
MySQL CRUD 核心指南:查询、插入、更新、删除全实战
android·开发语言·数据库·c++·人工智能·mysql
轩情吖11 分钟前
MySQL之表的约束
android·数据库·c++·后端·mysql·开发·约束
Rainman博15 分钟前
AMS-SplashScreen分析
android
常利兵1 小时前
AGP 9.0升级攻略:挥别技术旧疾,迎接开发新程
android
轩情吖1 小时前
MySQL内置函数
android·数据库·c++·后端·mysql·开发·函数
Digitally1 小时前
如何在安卓设备上将照片移动到SD卡
android
Kapaseker2 小时前
一杯半 Kotlin 美式详解 value class
android·kotlin
zhouping@2 小时前
[NPUCTF2020]ezinclude
android·web安全
廖圣平2 小时前
Drogon 现代化C ++高性能框架
android·c语言·开发语言