Kotlin操作Map值如何简化 无需中间变量实现键存在减1不存在设10
Kotlin 代码简化方案
方案1:空安全调用+Elvis运算符(最简洁,完全等价原有逻辑)
直接去掉中间变量,用?.let+?:组合实现判断,代码如下:
val map = mutableMapOf<String, String>() map["key"] = map["key"]?.let { (it.toInt() - 1).toString() } ?: "10"
逻辑说明:如果map["key"]不为空,就执行let代码块将值转整型减1后再转回字符串;如果为空,就直接返回默认值"10"赋值给对应key。
方案2:使用标准库compute方法
如果更喜欢显式的集合操作API,可以用compute方法实现:
val map = mutableMapOf<String, String>() map.compute("key") { _, oldValue -> oldValue?.let { (it.toInt() - 1).toString() } ?: "10" }
优化建议:调整Map值类型
如果业务允许,建议将Map的值类型改为Int,避免反复转字符串的开销,代码会更清爽:
val map = mutableMapOf<String, Int>() map["key"] = map["key"]?.minus(1) ?: 10
内容的提问来源于stack exchange,提问作者Violetta
相关产品推荐
相关产品推荐

