I created a map from two lists of mutable strings in Kotlin using:
val mapNames = mutableMapOf(Pair(initList, nameList))
When I try to access the values of one of the keys I have tried
print(mapNames.get("BB")) and print(mapNames["BB"])
and it throws the error
error: type inference failed. The value of the type parameter K should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly.
Both lists are lists of strings and I am just trying to simply return the value associated with the key. I have tried to explicitly specify its type as String and am still thrown an error. I am wondering what I am missing?
CodePudding user response:
You have not created a Map<String, String>
. You have created a Map<List<String>, List<String>>
. The only key in the map is initList
, and it corresponds to the value nameList
. That's obviously not what you want. You want each thing in initList
to match up with each thing in nameList
and form an entry in the map, so that you get a Map<String, String>
, right?
To do this, you should zip
the lists:
val mapNames = initList.zip(nameList).toMap(mutableMapOf())
zip
here creates a List<Pair<String, String>>
, and mutableMapOf
will turn each pair in that list into a map entry. Then you can access the map as expected.