Home > Blockchain >  Unresolved reference, type mismatch when trying to access an inner key
Unresolved reference, type mismatch when trying to access an inner key

Time:04-02

I have this map:

{aws={foo={dev={account_id=1234}, pre={account_id=5678}, prod={account_id=9999}}, bar={dev={account_id=22222}, pre={account_id=33333}, prod={account_id=4444}}}}```

I can access data.get("aws") without issues. However, data.get("aws").get("foo") reports:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
public inline operator fun <K, V> Map<out String, ???>.get(key: String): ??? defined in kotlin.collections
public operator fun MatchGroupCollection.get(name: String): MatchGroup? defined in kotlin.text

Why?

CodePudding user response:

The first get returns a nullable, meaning the result of map.get("aws") can be a map or null. As you can not apply .get(...) to null, you must tell the compiler how to handle it:

val map = mapOf(
  "aws" to mapOf(
    "foo" to mapOf(
      "dev" to mapOf("account_id" to 1234),
      "pre" to mapOf("account_id" to 5678),
      "prod" to mapOf("account_id" to 9999),
    ),
    "bar" to mapOf(
      "dev" to mapOf("account_id" to 22222),
      "pre" to mapOf("account_id" to 33333),
      "prod" to mapOf("account_id" to 4444),
    )
  )
)

// if you are sure that a key "aws" exists, you can do this:
val foo = map.get("aws")!!.get("foo")
// foo is a Map<String, Map<String, Int>>

// If you are not sure that a key "aws" will exist:
val foo = map.get("aws")?.get("foo")
// foo is a Map<String, Map<String, Int>>?

See Null Safety | Kotlin

  • Related