Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

generics - Returning same collection type, differently parameterised

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?

For example

def foo[A](xs: GenTraversable[A]) = xs map (_.toString)

foo( List(1, 2, 3) ) returns res: GenTraversable[String] = List(1, 2, 3)

Can this be adapted so that

foo( Set(1, 2, 3) ) returns a Set[String]

foo( List(1, 2, 3) ) returns a List[String]

foo( Vector(1, 2, 3) ) returns a Vector[String]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...