在 Kotlin 中访问地图中的值

Accessing the values inside a map in Kotlin

我在访问这个 dictionary/map 中的值时遇到困难 我在这个动物对象内部构建:

object Animals {
var animalInfo = mutableMapOf<String,Any>()
init {
    animalInfo["Animal"] = mutableListOf("description" to "Large Mammal", "name" to "Elephant", "highlights" to arrayListOf("Long Trunk", "Flappy Ears", "Ivory Tusks"))
    }
}    

Swift 作为我的第一语言,我尝试访问这样的值,但没有使用可选绑定:

 val dataDict = Animals.animalInfo
        val animal = dataDict["Animal"]
        println(animal["description"])
        println(animal["name"])
        println(animal["highLights"])

所有 println 行都有未解决的引用错误。如何正确访问 mutableMapOf() 中的值?

更改此行:

var animalInfo = mutableMapOf<String,Any>()

进入

var animalInfo = mutableMapOf<String,MutableMap<String, out Any>>()

并改变

val module = dataDict["Animal"]

进入

val module = dataDict["Animal"]!!

并将 mutableListOf 更改为 mutableMapOf 应该可以解决此问题(总共更改 3 个)。