Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Creating a mutable map from list of pairs, and not varargs?

Tags:

kotlin

I have a list in Kotlin. I need to create a map from every element of the list, to an empty mutable set, something like this -

var mutableMap: MutableMap<Int, MutableSet<Int>> = mutableMapOf(someList.map{ it to mutableSetOf<Int>() })

But I'm getting this error -

Type mismatch.
Required:
Pair<TypeVariable(K), TypeVariable(V)>
Found:
List<Pair<Int, MutableSet<Int>>>

I know that mutableMapOf() accepts varargs pairs, so I tried the spread operator (*), but that also didnt work. Please help me achieve the result.

like image 947
Dhruv Chadha Avatar asked Sep 17 '25 07:09

Dhruv Chadha


1 Answers

The spread operator is for Arrays, not Lists. Also, if you define your variable type as a Map of Sets instead of a MutableMap of MutableSets, you are casting it to be read-only. So to fix your code:

var mutableMap: MutableMap<Int, MutableSet<Int>> = mutableMapOf(*someList.map{ it to mutableSetOf<Int>() }.toTypedArray())

But it would be cleaner to do:

val map = someList.associateWith { mutableSetOf<Int>() }.toMutableMap()
like image 174
Tenfour04 Avatar answered Sep 19 '25 21:09

Tenfour04