简体   繁体   中英

Advantages of using this.type in Scala?

Here is an example from the stairway book:

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]
  }

}

Note that for the methods += and -= , the return types are this.type . Can I use PrefixMap[T] here? If yes, what does this.type has to offer?

Can I use PrefixMap[T] here?

Yes.

If yes, what does this.type has to offer?

For example, imagine you also have another class PrefixMap2[T] extending PrefixMap . Then with this.type , += and -= called on a PrefixMap2 will return itself (and therefore, a PrefixMap2 ); with PrefixMap return type, the compiler will only know they return a PrefixMap .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM