import scala.collection.mutable.{Builder, MapBuilder} import scala.collection.generic.CanBuildFrom
object PrefixMap extends {
def empty[T] = new PrefixMap[T]
def apply[T](kvs: (String, T)*): PrefixMap[T] = { val m: PrefixMap[T] = empty
for (kv <- kvs) m += kv m
}
def newBuilder[T]: Builder[(String, T), PrefixMap[T]] = new MapBuilder[String, T, PrefixMap[T]](empty)
implicit def canBuildFrom[T]
:CanBuildFrom[PrefixMap[_], (String, T), PrefixMap[T]] =
new CanBuildFrom[PrefixMap[_], (String, T), PrefixMap[T]] { def apply(from: PrefixMap[_]) = newBuilder[T]
def apply() = newBuilder[T]
}
}
Listing 25.11 · The companion object for prefix maps.
PrefixMap literals like you do for any other collection:
scala> PrefixMap("hello" -> 5, "hi" -> 2) res0: PrefixMap[Int] = Map((hello,5), (hi,2))
scala> PrefixMap.empty[String] res2: PrefixMap[String] = Map()
The other member in object PrefixMap is an implicit CanBuildFrom instance. It has the same purpose as the CanBuildFrom definition in the last section: to make methods like map return the best possible type. For instance, consider mapping a function over the key/value pairs of a PrefixMap. As long as that function produces pairs of strings and some second type, the result collection will again be a PrefixMap. Here’s an example:
scala> res0 map { case (k, v) => (k + "!", "x" * v) } res8: PrefixMap[String] = Map((hello!,xxxxx), (hi!,xx))