Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a mutable HashMap into an immutable equivalent in Scala?

Inside a function of mine I construct a result set by filling a new mutable HashMap with data (if there is a better way - I'd appreciate comments). Then I'd like to return the result set as an immutable HashMap. How to derive an immutable from a mutable?

like image 431
Ivan Avatar asked Jan 30 '12 00:01

Ivan


1 Answers

Discussion about returning immutable.Map vs. immutable.HashMap notwithstanding, what about simply using the toMap method:

scala> val m = collection.mutable.HashMap(1 -> 2, 3 -> 4)
m: scala.collection.mutable.HashMap[Int,Int] = Map(3 -> 4, 1 -> 2)

scala> m.toMap
res22: scala.collection.immutable.Map[Int,Int] = Map(3 -> 4, 1 -> 2)

As of 2.9, this uses the method toMap in TraversableOnce, which is implemented as follows:

def toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U] = {
    val b = immutable.Map.newBuilder[T, U]
    for (x <- self)
        b += x

    b.result
}
like image 185
ebruchez Avatar answered Nov 08 '22 14:11

ebruchez