scala: adding a method to List?

后端 未结 3 1813
深忆病人
深忆病人 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:42

    As already pointed out by Easy Angel, use implicit conversion:

    implicit def listTorichList[A](input: List[A]) = new RichList(input)
    
    class RichList[A](val source: List[A]) {
    
        def partitionCount(p: A => Boolean): (Int, Int) = {
            val partitions = source partition(p)
            (partitions._1.size, partitions._2.size)
        }
    }
    

    Also note that you can easily define partitionCount in terms of partinion. Then you can simply use:

    val list = List(1, 2, 3, 5, 7, 11)
    val (odd, even) = list partitionCount {_ % 2 != 0}
    

    If you are curious how it works, just remove implicit keyword and call the list2richList conversion explicitly (this is what the compiler does transparently for you when implicit is used).

    val (odd, even) = list2richList(list) partitionCount {_ % 2 != 0}
    

提交回复
热议问题