2015-10-18 24 views
0

下面是從樓梯書爲例:在Scala中使用this.type的優點?

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

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

是。

如果是,那麼這個類型必須提供什麼?

例如,假設您還有另一類PrefixMap2[T]延伸PrefixMap。然後與this.type+=-=呼籲PrefixMap2將返回本身(因此,PrefixMap2);與PrefixMap返回類型,編譯器將只知道他們返回PrefixMap

+0

不錯。但是,你如何解釋這個'def withPrefix(s:String):PrefixMap [T]'? – qed

+0

有什麼解釋?它不能有'this.type',因爲它並不總是返回'this'。 –