Juh_ Juh_ - 23 days ago 12
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
map
making whatever Seq then copying into a Vector.

Seq.map
takes an implicit
canBuilFrom
parameters which induces the collection output type. So I tried
s.map(...)(Vector.canBuildFrom[String])
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

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

Comments