Scala的可变队列在Map中是不可变的

时间:2015-02-27 19:20:45

标签: scala collections

我正在使用scala版本2.10.4,看起来Map中的collection.mutable.Queue不可变。然而,collection.mutable.Queue的关键元组似乎确实是可变的。

scala> scala.util.Properties.scalaPropOrEmpty("version.number")
res0: String = 2.10.4

scala> import scala.collection.mutable.{ Queue => MutableQueue }
import scala.collection.mutable.{Queue=>MutableQueue}

scala> (1 to 50).groupBy(_ % 5).mapValues(nums => MutableQueue(nums:_*))
res1: scala.collection.immutable.Map[Int,scala.collection.mutable.Queue[Int]] = Map(0 -> Queue(5, 10, 15, 20, 25, 30, 35, 40, 45, 50), 1 -> Queue(1, 6, 11, 16, 21, 26, 31, 36, 41, 46), 2 -> Queue(2, 7, 12, 17, 22, 27, 32, 37, 42, 47), 3 -> Queue(3, 8, 13, 18, 23, 28, 33, 38, 43, 48), 4 -> Queue(4, 9, 14, 19, 24, 29, 34, 39, 44, 49))

scala> res1(0).dequeue
res2: Int = 5

scala> res1(0)
res3: scala.collection.mutable.Queue[Int] = Queue(5, 10, 15, 20, 25, 30, 35, 40, 45, 50)

scala> (1 to 50).groupBy(_ % 5).mapValues(nums => MutableQueue(nums:_*)).toSeq
res4: Seq[(Int, scala.collection.mutable.Queue[Int])] = ArrayBuffer((0,Queue(5, 10, 15, 20, 25, 30, 35, 40, 45, 50)), (1,Queue(1, 6, 11, 16, 21, 26, 31, 36, 41, 46)), (2,Queue(2, 7, 12, 17, 22, 27, 32, 37, 42, 47)), (3,Queue(3, 8, 13, 18, 23, 28, 33, 38, 43, 48)), (4,Queue(4, 9, 14, 19, 24, 29, 34, 39, 44, 49)))

scala> res4.find(_._1 == 0).get._2.dequeue
res5: Int = 5

scala> res4.find(_._1 == 0).get._2
res6: scala.collection.mutable.Queue[Int] = Queue(10, 15, 20, 25, 30, 35, 40, 45, 50)

我希望res1(0)能反映出队名。

1 个答案:

答案 0 :(得分:4)

这是因为mapValues会返回一个视图,因此每次访问Queue时都会创建一个新的可变res1

您可以使用严格map来解决此问题。

scala> (1 to 50).groupBy(_ % 5).map { case (_, nums) => MutableQueue(nums:_*) }.toList
res20: List[scala.collection.mutable.Queue[Int]] = List(Queue(5, 10, 15, 20, 25, 30, 35, 40, 45, 50), Queue(1, 6, 11, 16, 21, 26, 31, 36, 41, 46), Queue(2, 7, 12, 17, 22, 27, 32, 37, 42, 47), Queue(3, 8, 13, 18, 23, 28, 33, 38, 43, 48), Queue(4, 9, 14, 19, 24, 29, 34, 39, 44, 49))

scala> res20(0).dequeue
res21: Int = 5

scala> res20(0)
res22: scala.collection.mutable.Queue[Int] = Queue(10, 15, 20, 25, 30, 35, 40, 45, 50)