7

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)?

sdkfasldf
  • 607
  • 6
  • 19

3 Answers3

14

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.

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
  • So it is a good practice to set all function parameter types to Iterable instead of specific types (unless you need them for some specific functionality/performance)? – sdkfasldf Mar 23 '12 at 05:03
  • 3
    If you need it to cover all Iterables then by all means do that, but the compiler won't complain when you pass your method a Map by mistake! I think in OO in general, the theory is that you're supposed to accept that most general type possible and return the most specific. With collections, making the accepted types too general will mean the returned type will also be very general (see this question: http://stackoverflow.com/q/8235462/770361). So in practice you methods taking `List` etc. `Seq` is a good compromise to use IMO. – Luigi Plinge Mar 23 '12 at 05:18
  • 4
    I think there ought to be `toVector` anyway. Sometimes this whole code-to-the-interface thing is important, like at API boundaries, but most of the time you're just trying to get work done and the lack of `toVector` is just annoying. `Vector` is a great general-purpose collection; the uses of `List` and `Array` are rather specialized. – Seth Tisue Mar 23 '12 at 12:02
  • @SethTisue - Agreed. I have a standard `toVector` enrichment. – Rex Kerr Mar 23 '12 at 15:15
3

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.

missingfaktor
  • 90,905
  • 62
  • 285
  • 365
1

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] 
Brent Faust
  • 9,103
  • 6
  • 53
  • 57