Created
January 29, 2019 01:20
-
-
Save fernandomora/5c94741353981241c76dc8270b5b8b6c to your computer and use it in GitHub Desktop.
Scala groupMap from 2.13 for scala 2.12
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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