Returning same collection type, differently parameterised

后端 未结 1 873
忘了有多久
忘了有多久 2020-12-18 10:52

Daniel Sobral showed how we can create a method that returns the same collection type upon which it was called in his answer to this question: Returning original collection

相关标签:
1条回答
  • 2020-12-18 11:24

    Extending Daniel's answer to the linked question:

    def foo[A,T[X] <: TraversableLike[X,T[X]]](xs: T[A])(implicit cbf: CanBuildFrom[T[A],String,T[String]]):  T[String] = xs.map(_.toString)
    

    Note that the map method defined in TraversableLike takes an implicit CanBuildFrom parameter. This is used to create a builder for the desired collection type so it has to be parameterized the way it is in the code (i.e., based on a collection of type T[A], build a T[String] from String elements).

    0 讨论(0)
提交回复
热议问题