我想知道如何向列表中添加一个'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)
  }
}

这是更通用的版本,对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)
  }
}

最佳答案

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

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

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

而不是this,您需要使用targetList。您不需要扩展List。在此示例中,我创建了将隐式使用的简单包装MyRichList

您可以通过为Traversable定义包装器来进一步概括包装器,以便它可以用于其他收集类型,而不仅适用于List:
implicit def listToMyRichTraversable[T](l: Traversable[T]) = new MyRichTraversable(l)

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

还要注意,仅当隐式转换在范围内时才使用。这意味着,您需要对其进行import(除非您在定义它的相同范围内使用它)。

关于scala:向List添加方法吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6975754/

10-12 02:57
查看更多