Skip to content

Instantly share code, notes, and snippets.

@guizmaii
Forked from fernandomora/GroupableOps.scala
Created April 16, 2019 13:22
Show Gist options
  • Save guizmaii/12d19bda2d97878a0ea6549752931bbe to your computer and use it in GitHub Desktop.
Save guizmaii/12d19bda2d97878a0ea6549752931bbe to your computer and use it in GitHub Desktop.
Scala groupMap from 2.13 for scala 2.12
import scala.collection.{immutable, mutable, GenTraversableOnce}
import scala.collection.generic.CanBuildFrom
object GroupableOps {
implicit class ToGroupable[A, Coll[X] <: GenTraversableOnce[X]](coll: Coll[A]) {
// https://github.com/scala/scala/blob/v2.13.0-M5/src/library/scala/collection/Iterable.scala#L578
def groupMap[K, B, To](key: A => K)(f: A => B)
(implicit bf: CanBuildFrom[Coll[A], B, To]): immutable.Map[K, To] = {
val m = mutable.Map.empty[K, mutable.Builder[B, To]]
for (elem <- coll) {
val k = key(elem)
val bldr = m.getOrElseUpdate(k, bf())
bldr += f(elem)
}
var result = immutable.Map.empty[K, To]
for ((k, v) <- m) {
result = result + ((k, v.result()))
}
result
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment