![](/img/trans.png)
[英]how to make Scala canBuildFrom to build collection type from Seq to Set
[英]How to choose the output collection type in Seq.map?
我想實現類似:
def f(s: Seq[Int]): Vector[String] = s.map(_.toString).toVector
但是我希望它直接創建輸出Vector,而無需先執行map
,無論將Seq做什么,然后再將其復制到Vector中。
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的第一個類型參數
那怎么辦呢?
您正在尋找breakOut
def f(s: Seq[Int]): Vector[String] = s.map(_.toString)(collection.breakOut)
有關breakOut
功能的深入討論,請查看以下StackOverflow問題: Scala 2.8 breakOut
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.