简体   繁体   English

在地图中时,Scala的可变队列不可变

[英]Scala's Mutable Queue isn't mutable when in a Map

I'm using scala version 2.10.4 and it appears that a collection.mutable.Queue inside a Map isn't mutable. 我正在使用Scala 2.10.4版本,并且Map中的collection.mutable.Queue似乎不可变。 However a tuple of key to collection.mutable.Queue does appear to be mutable. 但是,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)

I would expect that res1(0) should reflect the dequeue. 我希望res1(0)应该反映出队。

This is because mapValues returns a view, so a new mutable Queue is being created every time you access res1 . 这是因为mapValues返回一个视图,所以每次访问res1时都会创建一个新的可变Queue

You can fix this by using a strict map . 您可以使用严格的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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM