2013-08-27 25 views
0

我在listbuffer類型上使用prepend方法並觀察一些奇怪的行爲。 prepend操作返回一個可接受的新列表。但是不應該也修改ListBuffer?預先確定後,我仍然看到ListBuffer的長度沒有改變。我在這裏錯過了什麼嗎?Scala prepend +:op不修改ListBufffer

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) 
+3

通過它是工作的方式[在doc明確說明](http://take.ms/R5M6Ct) –

回答

7

使用+=:

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) 
+0

賓果。 – Shrikar