【问题标题】:How to choose the output collection type in Seq.map?如何在 Seq.map 中选择输出集合类型?
【发布时间】:2023-03-10 14:00:01
【问题描述】:

我想实现类似的东西:

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

但我希望它直接创建输出向量,而无需先执行map,制作任何 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 的第一个类型参数

如何做到这一点?

【问题讨论】:

    标签: scala generics collections


    【解决方案1】:

    breakOut 就是你要找的东西

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

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

    【讨论】:

    • 如果可以的话,我会投票两次。它使用起来非常简单,现在我的代码中都有collection.breakout :-)
    • @Juh_ 不客气!那你为什么从答案中删除接受的标记?尝试两次投票? :)
    • 对不起。我没有意识到我删除了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    相关资源
    最近更新 更多