简体   繁体   English

在Kotlin中访问地图内的值

[英]Accessing the values inside a map in Kotlin

I'm having difficulty accessing the values in this dictionary/map I built inside of this animals object: 我在访问此动物对象内部构建的字典/地图中的值时遇到困难:

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 being my first language I tried to access the values like this but without the use of optional binding: Swift是我的第一语言,我尝试访问这样的值,但没有使用可选绑定:

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

All the println lines have an unresolved reference error. 所有的println行都有一个未解决的参考错误。 How do I correctly access the values in a mutableMapOf()? 如何正确访问mutableMapOf()中的值?

Change this line: 更改此行:

var animalInfo = mutableMapOf<String,Any>()

into

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

and change 并改变

val module = dataDict["Animal"]

into

val module = dataDict["Animal"]!!

and change mutableListOf into mutableMapOf should resolve this (3 changes in total). 并将mutableListOf更改为mutableMapOf应该可以解决此问题(共3处更改)。

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

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