scala 将 Seq 转换为 ArrayBuffer

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7553255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:29:36  来源:igfitidea点击:

Convert Seq to ArrayBuffer

scalaseqarraybuffer

提问by classicalist

Is there any concise way to convert a Seqinto ArrayBufferin Scala?

有没有什么简洁的方法可以在 Scala 中将a 转换SeqArrayBuffer

回答by Eastsun

scala> val seq = 1::2::3::Nil
seq: List[Int] = List(1, 2, 3)

scala> seq.toBuffer
res2: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3)

EDITAfter Scala 2.1x, there is a method .to[Coll]defined in TraversableLike, which can be used as follow:

编辑Scala 2.1x 之后,.to[Coll]TraversableLike 中定义了一个方法,可以如下使用:

scala> import collection.mutable
import collection.mutable

scala> seq.to[mutable.ArrayBuffer]
res1: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)

scala> seq.to[mutable.Set]
res2: scala.collection.mutable.Set[Int] = Set(1, 2, 3)

回答by Philippe

This will work:

这将起作用:

ArrayBuffer(mySeq : _*)

Some explanations: this uses the apply method in the ArrayBuffer companion object. The signature of that method is

一些解释:这使用了ArrayBuffer 伴随对象中的 apply 方法。该方法的签名是

def apply [A] (elems: A*): ArrayBuffer[A]

meaning that it takes a variable number of arguments. For instance:

这意味着它需要可变数量的参数。例如:

ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8)

is also a valid call. The ascription : _* indicates to the compiler that a Seq should be used in place of that variable number of arguments (see Section 4.6.2 in the Scala Reference).

也是一个有效的调用。说明 : _* 向编译器指示应该使用 Seq 代替可变数量的参数(参见Scala 参考中的第 4.6.2 节)。