将元组附加到Scala中的缓冲区

时间:2013-07-29 16:18:16

标签: scala scala-collections

在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
}

为什么行

println(buffer += (2, 3))  

工作,但行

println(buffer += aTuple ) 

不编译?

1 个答案:

答案 0 :(得分:10)

由于您没有添加Tuple,因此您使用两个参数调用+=方法:

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

那个方法is defined既有varargs又有没有,并且在缓冲区中添加了所有内容:

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