如何在Seq.map中选择输出集合类型?

时间:2016-11-10 10:19:46

标签: scala generics collections

我想实现类似的东西:

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的第一个类型参数

怎么办呢?

1 个答案:

答案 0 :(得分:4)

breakOut正是您要找的

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

要深入讨论breakOut的作用,请查看此StackOverflow问题:Scala 2.8 breakOut