簡體   English   中英

如何在Seq.map中選擇輸出集合類型?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM