Home > Software design >  How do I populate a Mutable map using a loop in scala?
How do I populate a Mutable map using a loop in scala?

Time:08-20

import scala.collection.mutable.Map

var overlapByY: Map[Int, Int] = (0 to records.length).map(a => (a, 0)).toMap

Gives the error

polymorphic expression cannot be instantiated to expected type;
[error]  found   : Map          (in scala.collection.immutable)
[error]  required: Map[Int,Int] (in scala.collection.mutable)
[error]             var overlapByY: Map[Int, Int] = (0 to 8).map(a => (a, 0)).toMap
[error]                                                                       ^

CodePudding user response:

toMap explicitly results in an immutable Map (even though the implementation probably uses a mutable Map internally...)

There are a few ways to go about this. I would tend to use foldLeft:

import scala.collection.mutable

(0 to records.length)  // note that to is inclusive, 0 until records.length might actually be what you want...
  .foldLeft(mutable.Map.empty[Int, Int]) { (map, elem) =>
    map  = elem -> 0
  }

This would be equivalent to the even more imperative:

{
  val map = mutable.Map.empty[Int, Int]
  (0 to records.length).foreach { elem => map  = elem -> 0 }
  map
}

CodePudding user response:

toMap returns an immutable.Map so you can't use that if you want a mutable.Map. Use the to method with the mutable.Map object as parameter:

  val overlapByY: mutable.Map[Int, Int] =
    (0 to records.length).map(a => (a, 0)) to mutable.Map

Since it's mutable, you can make overlapByY a val, and still add elements to it:

  overlapByY  = ( 1 -> 2)

For older versions of Scala, the old way of doing this was by passing the result of the map as a repeated-parameter using _* to the apply method of the mutable.Map:

  val overlapByY2 =
    mutable.Map((0 to records.length).map(a => (a, 0)): _*)
  • Related