KarmaDeli
KarmaDeli

Reputation: 648

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()?

Upvotes: 1

Views: 7408

Answers (1)

ice1000
ice1000

Reputation: 6569

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).

Upvotes: 2

Related Questions