2

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 ?

Juh_
  • 14,628
  • 8
  • 59
  • 92

1 Answers1

4

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

Community
  • 1
  • 1
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235