How can a method accept (T <: Seq) [A] and return T [B] - the same sequence type with a different type parameter?

I want to implement a method that takes a sequence of one type of element and returns a sequence of another type of element. How can I do this in general to return the same subclass of a sequence?

Now my method is as follows:

 def lookerUpper(ids : Seq[String], someOtherInfo : Int) : Seq[UsefulData] = { ... retrieve data for each id ... } 

I would like it to be more general, so that any sequence (of lines) is also passed to the returned form (from the payload). Vector and List, especially, or as general as we can do this.

Can this be expressed in a system like Scala? "Returns the same type as this argument, except for another type parameter."

+4
source share
1 answer

For a complete answer, you should look at my rather long question and answer about the builders (note: as of September 2012, the alternative version of Miles does not work either in version 2.9 or in the latest version 2.10).

Here you can get started (pay attention to the strange formatting of explicit and implicit parameter blocks to avoid excessively long lines for displaying on SO):

 import collection.generic.CanBuildFrom case class UsefulData(data: Int) {} def lookerUpper[C[String]]( ids: C[String], someOtherInfo: Int )( implicit cbf: CanBuildFrom[C[String],UsefulData,C[UsefulData]], ev: C[String] => Iterable[String] ): C[UsefulData] = { val b = cbf() val i = ev(ids) i.foreach{ s => b += UsefulData(s.length + someOtherInfo) } b.result } 

And note that it works:

 scala> lookerUpper(Vector("salmon","cod"),2) res0: scala.collection.immutable.Vector[UsefulData] = Vector(UsefulData(8), UsefulData(5)) scala> lookerUpper(Array("salmon","cod"),2) res1: Array[UsefulData] = Array(UsefulData(8), UsefulData(5)) 

Edit: if you only care about subclasses of TraversableLike (which Array not), and you are going to use standard collection operations to do all the work, then you can use answer 8609398 , as Luigi points out. (Perhaps I should move this answer there as a different perspective.)

+3
source

Source: https://habr.com/ru/post/1435122/


All Articles