Zizheng Tai
Zizheng Tai

Reputation: 6616

Scala: .to[Seq] vs .toSeq on collections

What's the difference between someCollection.to[Seq] and someCollection.toSeq? One thing I noticed is that when called on a Map, .toSeq generally returns a Vector, while .to[Seq] usually returns an ArrayBuffer, but I'm not sure what it really means.

Upvotes: 2

Views: 1922

Answers (1)

Till Rohrmann
Till Rohrmann

Reputation: 13346

The to[T] method of Scala's collection is the more generic function. It requires as an implicit parameter a value of type CanBuildFrom[From, Elem, To] which defines how one can construct a collection To with elements of type Elem from From. Usually, the toSeq, toList, toMap, ... directly forward to this method, as it is the case for Set, for example.

However, some classes offer a special implementation for certain toXXX methods in order to be more efficient. This is the case for the toSeq implementation of the Map class which internally calls toBuffer. toBuffer returns an ArrayBuffer. In contrast to that, the more generic to[Seq] method will be called with a CanBuildFrom implicit value which returns a Vector collection which is immutable.

Upvotes: 6

Related Questions