Is there any concise way to convert a Seq
into ArrayBuffer
in Scala?
Asked
Active
Viewed 1.9k times
14

classicalist
- 235
- 1
- 2
- 10
-
1duplicate: http://stackoverflow.com/questions/3074118/scala-how-do-i-convert-a-mapint-any-to-a-sortedmap-or-a-treemap – kiritsuku Sep 26 '11 at 09:50
2 Answers
28
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)
EDIT After Scala 2.1x, there is a method .to[Coll]
defined in TraversableLike, which can be used as follow:
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)

Eastsun
- 18,526
- 6
- 57
- 81
12
This will work:
ArrayBuffer(mySeq : _*)
Some explanations: this uses the apply method in the ArrayBuffer companion object. The signature of that method is
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).

Philippe
- 9,582
- 4
- 39
- 59