sonix
sonix

Reputation: 243

Transform Seq[A] to Map[Int, Seq[A]]

How can I transform a Seq[A] to a Map[Int, Seq[A]] in Scala where the value of Int is a param of A (in a functional way) ?

Example:

val futures: Seq[Future[Seq[A]]] = ???
val gathered = Future.collect(futures)
gathered.map {
    res => {
       val myseq:Seq[A] = res.flatten
       myseq.map(a => (a.param, a)).toMap
    }
}

the resulting value would be Map[Int, A]. Instead I'd like to have a sequence of all A having the same Int param (Map[Int, Seq[A])

Upvotes: 0

Views: 128

Answers (1)

wheaties
wheaties

Reputation: 35980

You'll need to prove to the compiler that there is a parameter of type A that can be had which satisfies your condition:

trait Param[A]{
  def extract(that: A): Int
}

def seqToMap[A](seq: Seq[A])(implicit proof: Param[A]) = 
  seq groupBy (proof.extract)

Other than that, you could use structural types (which involve reflection and thus are really inadvisable for performance reasons.)

Upvotes: 0

Related Questions