【问题标题】:Scala prepend +: op not modifying the ListBuffferScala prepend +: op 不修改 ListBuffer
【发布时间】:2013-08-27 07:02:02
【问题描述】:

我在 listbuffer 类型上使用 prepend 方法并观察到一些奇怪的行为。前置操作返回一个可接受的新列表。但它不应该也修改 ListBuffer 吗?前置后,我仍然看到 ListBuffer 的长度没有改变。我在这里遗漏了什么吗?

scala> val buf = new ListBuffer[Int]
buf: scala.collection.mutable.ListBuffer[Int] = ListBuffer()

scala> buf += 1                 
res47: buf.type = ListBuffer(1)

scala>  buf += 2
res48: buf.type = ListBuffer(1, 2)

scala> 3 +: buf
res49: scala.collection.mutable.ListBuffer[Int] = ListBuffer(3, 1, 2)

scala> buf.toList
res50: List[Int] = List(1, 2)

【问题讨论】:

标签: scala prepend listbuffer


【解决方案1】:

使用+=:

scala> val buf = new ListBuffer[Int]
buf: scala.collection.mutable.ListBuffer[Int] = ListBuffer()

scala> buf += 1
res0: buf.type = ListBuffer(1)

scala> buf += 2
res1: buf.type = ListBuffer(1, 2)

scala> 3 +=: buf
res2: buf.type = ListBuffer(3, 1, 2)

scala> buf.toList
res3: List[Int] = List(3, 1, 2)

【讨论】:

  • +: 不会改变缓冲区本身,而是返回一个新的突变缓冲区的副本,然后您必须将其用作用例的替代品,或者使用 +=: 直接改变缓冲区
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 2011-09-28
  • 1970-01-01
  • 1970-01-01
  • 2014-04-11
相关资源
最近更新 更多