默认情况下在斯卡拉映射一个空的ListBuffer
我试图创建一个可变的Map
,默认情况下,当一个元素被请求时,它不会在地图中创建一个新的ListBuffer
。但是,当新地图返回为默认地图时,它不会保留在地图中。也许这就是它的工作方式,我想,但是当我用Int
而不是ListBuffer
进行测试时,它的确如我所愿。这里有一些代码来解释我的意思 - 我做错了什么?默认情况下在斯卡拉映射一个空的ListBuffer
首先,这里正在与Map[Int]
:
scala> val a = collection.mutable.Map(1 -> 1).withDefault(i => 0) a: scala.collection.mutable.Map[Int,Int] = Map(1 -> 1)
scala> a(1) += 1 // adding to an existing element works as expected
scala> a
res48: scala.collection.mutable.Map[Int,Int] = Map(1 -> 2)
scala> a(2) += 1 // what about adding to a non-existing element?
scala> a // the new element has been added to the map
res50: scala.collection.mutable.Map[Int,Int] = Map(1 -> 2, 2 -> 1)
现在有Map[ListBuffer[Int]]
:
scala> val b = collection.mutable.Map(1 -> collection.mutable.ListBuffer[Int]()).withDefault(i => collection.mutable.ListBuffer.empty[Int]) b: scala.collection.mutable.Map[Int,scala.collection.mutable.ListBuffer[Int]] = Map(1 -> ListBuffer())
scala> b(1) += 1 // appending to an existing element works as expected
res51: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1)
scala> b
res52: scala.collection.mutable.Map[Int,scala.collection.mutable.ListBuffer[Int]] = Map(1 -> ListBuffer(1))
scala> b(2) += 1 // but appending to a non-existing element...
res53: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1)
scala> b // leaves the map unchanged
res54: scala.collection.mutable.Map[Int,scala.collection.mutable.ListBuffer[Int]] = Map(1 -> ListBuffer(1))
回答:
的区别是:
在第一种情况下a(2)
是Int
。由于Int
没有+=
方法,因此a(2) += 1
等效于a(2) = a(2) + 1
等,a.update(2, a(2) + 1)
。 update
实际上改变了地图。
但ListBuffer[Int]
确实有+=
方法,让您的来电是a(2).+=(1)
,并且不设置a(2)
任何东西!
回答:
您可以使用getOrElseUpdate(key: A, op: => B)
您可以创建一个ListBuffer的新实例,当密钥不存在时。
E.g.
val m = collection.mutable.Map[Int, ListBuffer[Int]]() m.getOrElseUpdate(1, ListBuffer()) += 1
以上是 默认情况下在斯卡拉映射一个空的ListBuffer 的全部内容, 来源链接: utcz.com/qa/265630.html