簡體   English   中英

在Scala中使用this.type的優勢?

[英]Advantages of using this.type in 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提供什么?

我可以在這里使用PrefixMap [T]嗎?

是。

如果是,此this.type提供什么?

例如,假設您還有另一個擴展PrefixMapPrefixMap2[T] 然后使用this.type ,在PrefixMap2上調用+=-=將返回自身(因此,返回PrefixMap2 ); 如果使用PrefixMap返回類型,則編譯器將只知道它們返回PrefixMap

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM