Reputation: 15599
I'd like to implement something like:
def f(s: Seq[Int]): Vector[String] = s.map(_.toString).toVector
But I'd like it to create directly the output Vector without executing the map
first, making whatever Seq, before copying it 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 ?
Upvotes: 2
Views: 174
Reputation: 108169
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
Upvotes: 4