Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there no methods toVector (like toList, toArray) in standard collection types?

Tags:

scala

If we are supposed to use Vector as the default Sequence type, why are there no methods toVector (like toList, toArray) in standard collection types?

In prototyping stage, is it okay to conform all collections to Seq type and use toSeq on all collection-returns (cast everything to Seq)?

like image 461
sdkfasldf Avatar asked Mar 23 '12 04:03

sdkfasldf


3 Answers

Normally you should be more concerned with the interface that the collection implements rather than its concrete type, i.e. you should think in terms of Seq, LinearSeq, and IndexedSeq rather than List, Array, and Vector, which are concrete implementations. So arguably there shouldn't be toList and toArray either, but I guess they're there because they're so fundamental.

The toIndexedSeq method in practice provides you with a Vector, unless a collection overrides this in order to provide a more efficient implementation. You can also make a Vector with Vector() ++ c where c is your collection.

like image 74
Luigi Plinge Avatar answered Dec 02 '22 20:12

Luigi Plinge


Scala 2.10 will come with a method .to[C[_]] so that you can write .to[List], .to[Array], .to[Vector], or any other compatible C.

like image 20
missingfaktor Avatar answered Dec 02 '22 20:12

missingfaktor


Scala 2.10 adds not only .to[Vector], but .toVector, as well:

In TraversableOnce trait inherited by collections and iterators:

abstract def toVector: Vector[A] 
like image 37
Brent Faust Avatar answered Dec 02 '22 20:12

Brent Faust