Convert Seq to ArrayBuffer

classicalist picture classicalist · Sep 26, 2011 · Viewed 16.6k times · Source

Is there any concise way to convert a Seq into ArrayBuffer in Scala?

Answer

Eastsun picture Eastsun · Sep 26, 2011
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)