rickster26ter1
rickster26ter1

Reputation: 433

How to add key and value to map of list of lists in Kotlin?

I have a map of lists created, and I'm just trying to add to the map as such:

val bandMap: Map<Int,List<List<Int>>> = mutableMapOf()

val rsrpList = mutableListOf<Int>()
val rsrqList = mutableListOf<Int>()
val levelList = mutableListOf<Int>()
rsrpList.add(3)
rsrqList.add(4)
levelList.add(1)
val listOfLists = mutableListOf(rsrpList,rsrqList,levelList)
bandMap[3] = listOfLists

But "bandMap[3] = listOfLists" says there is mismatch.

No set method providing array access

Not sure where this would be? It seems as if it doesn't know I'm trying to map something. I tried the put method, but it doesn't seem to recognize it.

Thanks.

Edit:

Thanks Tenfour04 - you helped a ton!

Upvotes: 0

Views: 970

Answers (1)

Tenfour04
Tenfour04

Reputation: 93629

You have specified the outer map to be a read-only Map and the inner lists to be read-only Lists in your variable type here:

private val bandMap: MutableMap<Int,List<List<Int>>> = mutableMapOf()

Even though you are putting MutableLists into your map, they are up-cast to Lists when you retrieve them because of the property type of bandMap.

Specify MutableList as the type of the inner Lists if you need to mutate them:

private val bandMap: MutableMap<Int, List<MutableList<Int>>> = mutableMapOf()

or, if you also need to modify the outer list of the lists:

private val bandMap: MutableMap<Int, MutableList<MutableList<Int>>> = mutableMapOf()

Side note, this three dimensional collection structure is kind of confusing to work with (error-prone). You might be able to come up with a structure that uses a class to make it easier to reason about and work with. I don't really know what your structure represents, but here's a vague example:

class Band {
    val rsrpList = mutableListOf<Int>()
    val rsrqList = mutableListOf<Int>()
    val levelList = mutableListOf<Int>()
}

val bandMap: MutableMap<Int, Band> = mutableMapOf()
bandMap[3] = Band()

Upvotes: 1

Related Questions