2

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?

3
  • Can you try val myOutput = a.get("name") ? To access values of the Map object, you need to use the get() method Commented Dec 10, 2022 at 6:42
  • @KartikShandilya I've tried, but this doesn't work. The output is an error: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public operator fun MatchGroupCollection.get(name: String): MatchGroup? defined in kotlin.text Commented Dec 10, 2022 at 6:55
  • 1
    The problem is that your map has inconsistent value types. One of them is a Map, but the other is a String. So when you retrieve a value, it has the common supertype, Any. Commented Dec 10, 2022 at 6:59

1 Answer 1

3

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.