在Scala中使用this.type的优点?

时间:2015-10-18 14:33:12

标签: 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 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))
      }
    }

    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
    }

    override def empty = new PrefixMap[T]
  }

}

请注意,对于方法+=-=,返回类型为this.type。我可以在这里使用PrefixMap[T]吗?如果是,this.type必须提供什么?

1 个答案:

答案 0 :(得分:1)

  

我可以在这里使用PrefixMap [T]吗?

  

如果是的话,this.type必须提供什么?

例如,假设您还有另一个PrefixMap2[T]个扩展PrefixMap的班级。然后使用this.type+=上调用的-=PrefixMap2将返回自身(因此,PrefixMap2);使用PrefixMap返回类型,编译器只会知道它们返回PrefixMap