繁体   English   中英

在Kotlin中访问地图内的值

[英]Accessing the values inside a map in Kotlin

我在访问此动物对象内部构建的字典/地图中的值时遇到困难:

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处更改)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM