Juh_ Juh_ - 1 year ago 69
Scala Question

How to choose the output collection type in Seq.map?

I'd like to implement something like:

def f(s: Seq[Int]): Vector[String] = s.map(_.toString).toVector

But without executing first
making whatever Seq then copying into a Vector.

takes an implicit
parameters which induces the collection output type. So I tried
which gives the error:

found : scala.collection.generic.CanBuildFrom[Vector.Coll,String,scala.collection.immutable.Vector[String]]
(which expands to) scala.collection.generic.CanBuildFrom[scala.collection.immutable.Vector[_],String,scala.collection.immutable.Vector[String]]
required: scala.collection.generic.CanBuildFrom[Seq[Int],String,Vector[String]]
def f(s: Seq[Int]): Vector[String] = s.map(_.toString)(Vector.canBuildFrom[String])

Basically it doesn't infer correctly the first type argument of the CanBuildFrom

How can that be done ?

Answer Source

breakOut is what you're looking for

def f(s: Seq[Int]): Vector[String] = s.map(_.toString)(collection.breakOut)

For an in-depth discussion of what breakOut does, check out this StackOverflow question: Scala 2.8 breakOut

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download