3
votes

What is the most effective way of conversion between different scala.collection object?

E.g.

 val a=scala.collection.mutable.ListBuffer(1,2,0,3)

And I want to get scala.collection.mutable.ArrayBuffer.

  1. According to http://docs.scala-lang.org/resources/images/collections.mutable.png it should be possible by converting to Buffer and to ArrayBuffer afterwards. Correct?

  2. In general, can i make any conversion in scala collection through its common ancestor? (in the previous example the common ancestor is Buffer)

PS I read http://docs.scala-lang.org/overviews/collections/introduction.html but couldn't find anything about general conversions between various types (i'm aware about .toArray like methods)

thx

2

2 Answers

3
votes

Syntax-wise most effective should be the to method introduced in 2.10:

def to[Col[_]]: Col[A]

Converts this collection into another by copying all elements. Note: will not terminate for infinite-sized collections.

Use it as a.to[scala.collection.mutable.ArrayBuffer].

Efficiency-wise, unless you do an upcast-like conversion where you turn a subtype into a more general collection, converting will involve copying the elements. In your example, it does not matter if you turn the list buffer into a buffer and then into an array buffer -- you can do this directly using to, as you cause copying the elements from a linked list into an array either way.

1
votes

Answering question number 2:

Welcome to Scala version 2.10.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_07).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import collection.mutable._
import collection.mutable._

scala> List(1,2,3,4,5)
res0: List[Int] = List(1, 2, 3, 4, 5)

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

scala> res0.to[ListBuffer]
res2: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 5)

You can convert them as you'd like as long as you keep compatibility:

scala> res0.to[Map]
<console>:12: error: scala.collection.mutable.Map takes two type parameters, expected: one
              res0.to[Map]
                      ^