简体   繁体   中英

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:

 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. How do I correctly access the values in a 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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