You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose mutableStateMapOf包装Map取值抛异常问题咨询

SnapshotStateMap访问不存在键抛出异常问题解析

问题描述

标准Kotlin的Map在访问不存在的键时,get方法(即map[key]语法)应当返回null,但使用Jetpack Compose的mutableStateMapOf初始化的SnapshotStateMap调用myMapOfThings["item3"]时,却抛出了java.util.NoSuchElementException: Key item3 is missing in the map.异常。

ViewModel中的初始化代码:

var myMapOfThings: MutableMap<String, MyType> by mutableStateMapOf(
    "item1" to MyType(),
    "item2" to MyType()
)

根据Kotlin标准库文档,kotlin.collections.Map的get方法明确约定不存在对应键时返回null:

/**
* Returns the value corresponding to the given [key], or `null` if such a key is not present in the map.
*/
public operator fun get(key: K): V?

相关构建信息:

kotlin_version = '1.8.0'
kotlin_plugin_version = '1.7.0'
compose_version = '1.2.0'
coroutines_version = '1.6.1'

compileSdk 32
buildToolsVersion = "30.0.3"
minSdk 28
targetSdk 32

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

kotlinOptions {
    jvmTarget = '1.8'
}

问题原因与解决办法

这并非Bug,而是由两方面因素导致:

1. 误用委托关键字by

你错误地使用by关键字初始化myMapOfThings。mutableStateMapOf直接返回SnapshotStateMap实例,并非委托属性所需的ReadWriteProperty实现。这种写法会干扰属性访问逻辑,引发非预期异常。

修正后的初始化代码:

// 直接赋值,无需by关键字
val myMapOfThings = mutableStateMapOf(
    "item1" to MyType(),
    "item2" to MyType()
)

2. 旧版本Compose的实现瑕疵

你使用的Compose 1.2.0版本中,SnapshotStateMap未严格遵循KotlinMap接口约定:访问不存在的键时未返回null,而是抛出异常。该问题已在Compose 1.3.0及以上版本中修复,新版本的SnapshotStateMap会正确返回null。

解决办法:
若修正代码后问题仍存在,将Compose版本升级至1.3.0或更高即可解决该兼容性问题。

内容的提问来源于stack exchange,提问作者ScottyC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:55:21