Appending tuple to a buffer in Scala

 ̄綄美尐妖づ 提交于 2019-12-10 16:46:15

问题


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 does line

println(buffer += (2, 3))  

work, but line

println(buffer += aTuple ) 

not compile ?


回答1:


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

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

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

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


来源:https://stackoverflow.com/questions/17929056/appending-tuple-to-a-buffer-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!