我想实现类似的东西:
def f(s: Seq[Int]): Vector[String] = s.map(_.toString).toVector
但我希望直接创建输出Vector而不先执行map
,在将其复制到Vector之前制作任何Seq。
Seq.map
采用隐式canBuilFrom
参数,这些参数会导致集合输出类型。所以我尝试了s.map(...)(Vector.canBuildFrom[String])
,它给出了错误:
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])
基本上它没有正确推断出CanBuildFrom的第一个类型参数
怎么办呢?
答案 0 :(得分:4)
breakOut
正是您要找的
def f(s: Seq[Int]): Vector[String] = s.map(_.toString)(collection.breakOut)
要深入讨论breakOut
的作用,请查看此StackOverflow问题:Scala 2.8 breakOut