1

This is the code block I have tried to understand += and ++=

scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> val a = ArrayBuffer[Int]()
a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()


scala> a += 1
res0: a.type = ArrayBuffer(1)

scala> a += (2,3,4);
res1: a.type = ArrayBuffer(1, 2, 3, 4)

scala>  a ++= Array(5,6,7)
res4: a.type = ArrayBuffer(1, 2, 3, 4, 5, 6, 7)

what is ++= operator in scala? How does it work? Why val is allowing merging of another array since val type should be constant and not against statically scoped feature?

0

1 Answer 1

2

For adding elements to ArrayBuffer, you are using three different functions there.

++=, from doc

def ++=(xs: TraversableOnce[A]): ArrayBuffer.this.type

Appends a number of elements provided by a traversable object.

+=, from doc

def +=(elem: A): ArrayBuffer.this.type

Appends a single element to this buffer and returns the identity of the buffer.

and a overloaded +=, from doc

def +=(elem1: A, elem2: A, elems: A*): ArrayBuffer.this.type

adds two or more elements to this growable collection.

The val a is immutable and you are actually adding elements to mutable ArrayBuffer, without changing the reference to variable a.

Edit

scala> val a = ArrayBuffer[Int]()
a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

scala> a += 1
res1: a.type = ArrayBuffer(1)

scala> a
res38: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1)

scala> a = ArrayBuffer[Int]()
<console>:33: error: reassignment to val
       a = ArrayBuffer[Int]()
         ^

As seen above when you are using +=, you are not changing the underlying reference to val a.

Sign up to request clarification or add additional context in comments.

2 Comments

ArrayBuffer and Array are different types. So addition of them allowed for val type variable is my query. I heard that Scala is statically scoped langugage
ArrayBuffer is a buffer backed by an array. They are both mutable datastructures, so yes, you can add elements to them. On the other hand you cant reassign val a as its immutable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.