Adding a tuple to a buffer in Scala

In Scala,

test("Appending a tuple to a Buffer"){ val buffer = ArrayBuffer[Int]() val aTuple = (2, 3) println(buffer += (2, 3)) // Result : ArrayBuffer(2, 3) println(buffer += aTuple ) // doesn't compile } 

Why line

 println(buffer += (2, 3)) 

works but string

 println(buffer += aTuple ) 

not compiling?

+4
source share
1 answer

Since you are not adding Tuple , you are calling the += method with two parameters:

 buffer += (3, 4) // is equivalent here to buffer.+=(3, 4) 

And this method is defined both with varargs and without it and adds to the buffer everything that is given to it:

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

Source: https://habr.com/ru/post/1494097/


All Articles