Home > Back-end >  Accessing fields from the values of a Map in Kotlin fails
Accessing fields from the values of a Map in Kotlin fails

Time:10-03

I am having the following two classes:

class A() {
  val name = "A"
}
class B() {
  val name = "B"
}

Then I create a map with instances of those two classes as values of the Map.

var m = mapOf("1" to A(), "2" to B())

Then I try to access the field name from the values of this map.

for ((k, v) in m) {
     println(v.name)
}

And I get this error:

error: unresolved reference: name
    println(v.name)

How do I access the field, and why do I get this error?

CodePudding user response:

Because you map to two different classes it can only conclude that you are mapping to the class Any which is the only class they both share, which doesn't have the field name. To solve it you can let both classes implement a common interface, like this

interface HasName {
    val name : String
}

class A : HasName {
    override val name = "A"
}
class B  : HasName {
    override val name = "B"
}

After this the compiler recognizes that you are mapping to objects that implement HasName and your code will work fine

CodePudding user response:

Ok first you need to know that map contains a key and a value and each one must have a type for example: (Map<String, Int> so the key must be a string and the value must be an Int).

Now for you case the map is: var m = mapOf("1" to A(), "2" to B()) the key is of type String but the value is of type A in the first element and of type B in the second element, so the compiler will specify the type Any to the value so your map is of type: Map<String, Any>, that's why when you try to access v.name you can't because in type Any there nothing called name.

To fix this problem you can use inheritance, you can create an interface:

interface X {
    val name: String
}

class A(): X {
    override val name = "A"
}
class B(): X {
    override val name = "B"
}

So now your map will be of type Map<String, X> because both A and B are of type X and you will be able to get access to name

  • Related