Android 写入嵌套字典(Kotlin)

Android 写入嵌套字典(Kotlin),android,dictionary,kotlin,Android,Dictionary,Kotlin,我已经用Swift声明了一个字典:private val nestedDictionary=mutableMapOf() 我现在要做的是写嵌套字典。下面是我正在使用的代码。 nestedDictionary[“第一层”][“第二层”]=mutableListOf(“写入失败”) 我试图做的是为[“第一层”]创建一个字典键,然后将值映射到其中。我该怎么做 编辑:我当前拥有并收到此错误的代码:“表达式不能是选择器。”一些脏的解决方案: nestedDictionary["First Layer"]?

我已经用Swift声明了一个字典:
private val nestedDictionary=mutableMapOf()

我现在要做的是写嵌套字典。下面是我正在使用的代码。
nestedDictionary[“第一层”][“第二层”]=mutableListOf(“写入失败”)

我试图做的是为[“第一层”]创建一个字典键,然后将值映射到其中。我该怎么做

编辑:我当前拥有并收到此错误的代码:“表达式不能是选择器。”

一些脏的解决方案:

nestedDictionary["First Layer"]?.put("Second Layer", mutableListOf("Failing to Write"))
// Map.get() is nullable

nestedDictionary[“第一层”]
可以返回一个not
null
值。因此,您不能链接
nestedDictionary[“第一层”][“第二层”]
,因为这意味着存储在
nestedDictionary[“第一层”]
的值存在

您可以使用强制执行代码。但是,如果
nestedDictionary[“First Layer”]
处的值以前未初始化,您将得到一个
KoltinNullPointerException

val nestedDictionary = mutableMapOf<String, MutableMap<String, List<String>>>()
nestedDictionary["First Layer"]!!["Second Layer"] = mutableListOf("possible to write")
这是因为中间的映射已初始化

val nestedDictionary = mutableMapOf<String, MutableMap<String, List<String>>>()
nestedDictionary["First Layer"] = HashMap()
nestedDictionary["First Layer"]!!["Second Layer"] = mutableListOf("possible to insert")
val nestedDictionary=mutableMapOf()
nestedDictionary[“第一层”]=HashMap()
nestedDictionary[“第一层”]!![“第二层”]=mutableListOf(“可插入”)
更清洁的解决方案是

val nestedDictionary = mutableMapOf<String, MutableMap<String, MutableList<String>>>()
nestedDictionary["First Layer"] = mutableMapOf("Second Layer" to mutableListOf("inserted"))
val nestedDictionary=mutableMapOf()
nestedDictionary[“第一层”]=mutableMapOf(“第二层”到mutableListOf(“插入”))

@Simulant的回答将覆盖
“第一层”
的现有值(如果有)。如果这不是您想要的,请使用:


投票结果:我喜欢
nestedDictionary[“第一层”]的干净解决方案!![“第二层”]
。如果项目不存在,我如何将其附加到[“第二层”]/的可变映射中/创建它?
Exception in thread "main" kotlin.KotlinNullPointerException
    at main(Main.kt:4)
val nestedDictionary = mutableMapOf<String, MutableMap<String, List<String>>>()
nestedDictionary["First Layer"] = HashMap()
nestedDictionary["First Layer"]!!["Second Layer"] = mutableListOf("possible to insert")
val nestedDictionary = mutableMapOf<String, MutableMap<String, MutableList<String>>>()
nestedDictionary["First Layer"] = mutableMapOf("Second Layer" to mutableListOf("inserted"))
nestedDictionary.getOrPut("First Layer", { mutableMapOf() })["Second Layer"] = 
    mutableListOf("Failing to Write")