接收"前缀映射"并返回空的"前缀映射"有什么意义?

  • 本文关键字:前缀 映射 返回 接收 scala
  • 更新时间 :
  • 英文 :


下面是楼梯书中的一个例子:

object Example1 {
  import collection._
  class PrefixMap[T]
    extends mutable.Map[String, T]
    with mutable.MapLike[String, T, PrefixMap[T]] {
    var suffixes: immutable.Map[Char, PrefixMap[T]] = Map.empty
    var value: Option[T] = None
    def get(s: String): Option[T] = {
      // base case, you are at the root
      if (s.isEmpty) value
      // recursive
      else suffixes get (s(0)) flatMap (_.get(s substring 1))
    }
    def iterator: Iterator[(String, T)] = {
      (for (v <- value.iterator) yield ("", v)) ++
        (for ((chr, m) <- suffixes.iterator; (s, v) <- m.iterator) yield (chr +: s, v))
    }
    def +=(kv: (String, T)): this.type = {
      update(kv._1, kv._2)
      this
    }
    def -=(key: String): this.type = {
      remove(key)
      this
    }

    def withPrefix(s: String): PrefixMap[T] = {
      if (s.isEmpty) this
      else {
        val leading = s(0)
        suffixes get leading match {
          case None => {
            // key does not exist, create it
            suffixes = suffixes + (leading -> empty)
          }
          case _ =>
        }
        // recursion
        suffixes(leading) withPrefix (s substring 1)
      }
    }
    override def update(s: String, elem: T) = {
      withPrefix(s).value = Some(elem)
    }
    override def remove(key: String): Option[T] = {
      if (key.isEmpty) {
        // base case. you are at the root
        val prev = value
        value = None
        prev
      } else {
        // recursive
        suffixes get key(0) flatMap (_.remove(key substring 1))
      }
    }
    override def empty = PrefixMap.empty
  }
  import collection.mutable.{Builder, MapBuilder}
  import collection.generic.CanBuildFrom
  object PrefixMap {
    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 mutable.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]
      }
    }
  }
}

我不明白这句话:

        def apply(from: PrefixMap[_]) = newBuilder[T]

接收一个PrefixMap而返回一个空的PrefixMap有什么意义?

多读一点官方文档

简而言之:CBF可以返回具有整个集合属性知识的构建器。
例如,它可以预先初始化所需大小的缓冲区来收集条目。
或者甚至重用已知类型和结构集合的某些部分。

但是在默认情况下,它将逐个元素收集到空集合。