scala: adding a method to List?

后端 未结 3 1796
深忆病人
深忆病人 2021-01-13 11:55

I was wondering how to go about adding a \'partitionCount\' method to Lists, e.g.: (not tested, shamelessly based on List.scala):

Do I have to create my own sub-clas

3条回答
  •  渐次进展
    2021-01-13 12:50

    You can use implicit conversion like this:

    implicit def listToMyRichList[T](l: List[T]) = new MyRichList(l)
    
    class MyRichList[T](targetList: List[T]) {
        def partitionCount(p: T => Boolean): (Int, Int) = ...
    }
    

    and instead of this you need to use targetList. You don't need to extend List. In this example I create simple wrapper MyRichList that would be used implicitly.

    You can generalize wrapper further, by defining it for Traversable, so that it will work for may other collection types and not only for Lists:

    implicit def listToMyRichTraversable[T](l: Traversable[T]) = new MyRichTraversable(l)
    
    class MyRichTraversable[T](target: Traversable[T]) {
        def partitionCount(p: T => Boolean): (Int, Int) = ...
    }
    

    Also note, that implicit conversion would be used only if it's in scope. This means, that you need to import it (unless you are using it in the same scope where you have defined it).

提交回复
热议问题