2

我在 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)
4

1 回答 1

12

利用+=:

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)
于 2013-08-27T07:17:10.213 回答