what is the difference between a “trait” and a “template trait”?

前端 未结 3 1477
长发绾君心
长发绾君心 2021-01-31 04:42

Looking at the scaladoc for Traversable and TraversableLike, I\'m having a hard time figuring out what the difference between them is (except that one extends the other). The o

3条回答
  •  误落风尘
    2021-01-31 05:21

    The XXXLike traits have an important role of adding the Repr generic parameter. Methods that are supposed to return the same collection type, like filter, map, flatMap, are implemented in low level traits (TraversableLike). To encode their return type, those traits receive it:

    trait TraversableLike[+A, +Repr] ...
      ...
      def filter(p: A => Boolean): Repr = {
    

    (for map and flatMap the issue is more complicated, I won't go into it here)

    Now say you have a new type of collection. You could do:

     trait MyCollection[+A] extends TraversableLike[A, MyCollection]
    

    But then if anyone wants to extend your collection, they are stuck with return values of MyCollection from the various inherited methods.

    So instead, you create:

     trait MyCollectionLike[+A, +Repr] extends TraversableLike[A, Repr]
    

    and

     trait MyCollection[+A] extends MyCollectionLike[A, MyCollection]
    

    and anyone that wants to extend your collection extends MyCollectionLike

提交回复
热议问题