返回相同的集合类型,参数化不同 [英] Returning same collection type, differently parameterised
问题描述
Daniel Sobral展示了我们如何创建一个方法来返回在回答此问题时调用的相同集合类型:在通用方法中返回原始集合类型
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 type in generic method
是否可以对使用映射返回不同参数化版本的方法集合类型?
Is it possible to do the same for a method that uses a mapping to return a differently-parameterized version of the same collection type?
例如
def foo[A](xs: GenTraversable[A]) = xs map (_.toString)
foo(List(1,2,3))
返回 res:GenTraversable [String] = List(1,2,3)
可以进行修改,以便
foo(Set(1,2,3))
返回 Set [String]
(1,2,3))
返回 List [String]
code> foo(Vector(1,2,3))返回 Vector [String]
foo( Vector(1, 2, 3) )
returns a Vector[String]
推荐答案
延伸Daniel对连结问题的回答:
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)
请注意, map $ c在
中定义的$ c>方法采用隐式 TraversableLike
CanBuildFrom
参数。
这用于为所需的集合类型创建一个构建器,因此必须按照它在代码中的方式进行参数化(即基于 T [A]
,构建 T [String]
从 String
元素)。
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).
这篇关于返回相同的集合类型,参数化不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!