Home > database >  how to access a value in a map that is nested inside another map (in kotlin)
how to access a value in a map that is nested inside another map (in kotlin)

Time:12-10

In the example below, a map called someCompany have a map called somePerson in one of its values

val somePerson = mapOf("name" to "Tim", "age" to "35")

val someCompany = mapOf("boss" to somePerson, "sector" to "accounting")

I thought it would be simple to get a value inside the nested map. I'm kind of surprised this naive solution doesn't work:


val a = someCompany["boss"]

val myOutput = a["name"] //I expected myOutput to be 'Tim', but this doesn't work 

How can I extract a value inside a nested map?

CodePudding user response:

You have to declare your maps like this:

val somePerson = mapOf("name" to "Tim", "age" to "35")
val otherPerson = mapOf("name" to "Tom", "age" to "25")

val someCompany = mapOf("boss" to somePerson, "sector" to otherPerson)

your sameCompany map needs to have the same type of data to work properly

and you can access name of the person by using get() method:

val person = someCompany["boss"]
val name = person?.get("name")

P.S.: if you really want to create your map with different types of data, you can cast retrieved value to your preferred type(but I wouldn't recommend it, as it is unsafe):

val person = someCompany["boss"] as? Map<String, String>
val name = person?.get("name")
  • Related