Hackaholic
Hackaholic

Reputation: 19763

Scala Map[String, MutableList]()

I want to create mutable Map which contains string as key and MutableList as value.

val myMap = scala.collection.mutable.Map[String, MutableList]()

like this:

mymap = Map("a" -> MutableList(1, 2, 3), "b" -> MutableList(5, 6, 7))

but whne i try to create it raises error:

scala> var myval = scala.collection.mutable.Map[String, scala.collection.mutable.MutableList]()
<console>:10: error: class MutableList takes type parameters
   var myval = scala.collection.mutable.Map[String, scala.collection.mutable.MutableList]()

Upvotes: 2

Views: 968

Answers (2)

Markus1189
Markus1189

Reputation: 2869

I don't share @jarandaf's point of view about var and mutable state:

You should use a var for mutable state and not val as well

For me using var is orthogonal to using a mutable data structure. There is no problem at all using it like this:

scala> import scala.collection.mutable.{Map => MutableMap, MutableList}
scala> val myMap = MutableMap("a" -> MutableList(1, 2, 3), "b" -> MutableList(5, 6, 7))

And you can still change the values of the map (never use a mutable value as the key unless you want to have some fun debugging) using mutation like this:

scala> myMap.get("a").map(_ += 42)
scala> myMap
res1: MutableMap[String,MutableList[Int]] = Map("b" -> MutableList(5, 6, 7), "a" -> MutableList(1, 2, 3, 42))

Actually if I use a var I normally use an immutable data structure because for me there is seldom a reason to use both a var and a mutable data structure.

scala> var myMap2 = Map("a" -> List(1,2,3))
scala> myMap2 = myMap2.updated("a",myMap2("a") :+ 42)
myMap2: scala.collection.immutable.Map[String,List[Int]] = Map(a -> List(1, 2, 3, 42))

Upvotes: 0

jarandaf
jarandaf

Reputation: 4427

MutableList[A] expects a type paremeter. You should use a var for mutable state and not val as well:

import scala.collection.mutable.{Map => MutableMap, MutableList}

var myMap = MutableMap[String, MutableList[Int]]()
myMap = MutableMap("a" -> MutableList(1, 2, 3), "b" -> MutableList(5, 6, 7))

Upvotes: 3

Related Questions