scala:向List添加方法?

Eri*_*ikR 5 scala

我想知道如何在列表中添加'partitionCount'方法,例如:(未经过测试,无耻地基于List.scala):

我是否必须创建自己的子类和隐式类型转换器?

(我最初的尝试有很多问题,所以这里有一个基于@Easy的答案):

class MyRichList[A](targetList: List[A]) {
  def partitionCount(p: A => Boolean): (Int, Int) = {
    var btrue = 0
    var bfalse = 0
    var these = targetList
    while (!these.isEmpty) {
      if (p(these.head)) { btrue += 1 }  else { bfalse += 1 }
      these = these.tail
    }
    (btrue, bfalse)
  }
}
Run Code Online (Sandbox Code Playgroud)

这是一个更适合Seq [...]的通用版本:

implicit def seqToRichSeq[T](s: Seq[T]) = new MyRichSeq(s)

class MyRichList[A](targetList: List[A]) {
  def partitionCount(p: A => Boolean): (Int, Int) = {
    var btrue = 0
    var bfalse = 0
    var these = targetList
    while (!these.isEmpty) {
      if (p(these.head)) { btrue += 1 }  else { bfalse += 1 }
      these = these.tail
    }
    (btrue, bfalse)
  }
}
Run Code Online (Sandbox Code Playgroud)

ten*_*shi 9

你可以像这样使用隐式转换:

implicit def listToMyRichList[T](l: List[T]) = new MyRichList(l)

class MyRichList[T](targetList: List[T]) {
    def partitionCount(p: T => Boolean): (Int, Int) = ...
}
Run Code Online (Sandbox Code Playgroud)

而不是this你需要使用targetList.你不需要扩展List.在这个例子中,我创建了一个MyRichList隐式使用的简单包装器.

您可以通过定义包装器来进一步概括包装器Traversable,以便它可以用于其他集合类型,而不仅仅适用于Lists:

implicit def listToMyRichTraversable[T](l: Traversable[T]) = new MyRichTraversable(l)

class MyRichTraversable[T](target: Traversable[T]) {
    def partitionCount(p: T => Boolean): (Int, Int) = ...
}
Run Code Online (Sandbox Code Playgroud)

另请注意,只有在范围内时才会使用隐式转换.这意味着,您需要import它(除非您在已定义它的同一范围内使用它).