Dhruv Chadha
Dhruv Chadha

Reputation: 1177

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

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.

Upvotes: 4

Views: 12054

Answers (4)

borjab
borjab

Reputation: 11685

Another option is:

var mutableMap = someList.associateTo(mutableMapOf())
          {it to mutableSetOf<Int>() }

This avoids having to create an intermediate map.

Upvotes: 0

Tenfour04
Tenfour04

Reputation: 93902

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()

Upvotes: 9

Nataraj KR
Nataraj KR

Reputation: 1102

val mutableMap: Map<Int, MutableSet<Int>> = someIntList.associateWith { mutableSetOf<Int>() }

Upvotes: 3

gidds
gidds

Reputation: 18627

You don't need to use mutableMapOf() with arguments; there's a handy extension function on the list which can do it for you: toMap().

Unfortunately, there's no corresponding toMutableMap().  One way would be to convert to a read-only map, and then convert that to a mutable map:

val mutableMap = someList.toMap().toMutableMap()

A slightly more complex but more efficient way would be to provide the resulting map:

val mutableMap = someList.toMap(mutableMapOf())

Upvotes: 6

Related Questions