Scala prepend +: op not modifying the ListBufffer

2k views Asked by At

I am using the prepend method on the listbuffer type and observing some weird behavior. The prepend operation returns a new list which is acceptable . But shouldn't it also modify the ListBuffer ? After prepending I am still seeing that the length of the ListBuffer is not changed. Am I missing something here?

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)
1

There are 1 answers

1
1esha On

Use +=:

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)