接收“PrefixMap”并返回空的“PrefixMap”是什么意思?

时间:2015-10-18 21:49:15

标签: 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时有什么意义?

1 个答案:

答案 0 :(得分:0)

多读一点official docs

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

但默认情况下,在很多情况下,它只是逐个元素地收集空集合。这种情况正在你的情况下发生。