scala:向List添加方法?
发布时间:2020-12-16 18:42:17 所属栏目:安全 来源:网络整理
导读:我想知道如何在列表中添加’partitionCount’方法,例如: (未经过测试,无耻地基于List. scala): 我是否必须创建自己的子类和隐式类型转换器? (我最初的尝试有很多问题,所以这里有一个基于@Easy的答案): class MyRichList[A](targetList: List[A]) { def p
我想知道如何在列表中添加’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,bfalse) } } 解决方法
你可以像这样使用隐式转换:
implicit def listToMyRichList[T](l: List[T]) = new MyRichList(l) class MyRichList[T](targetList: List[T]) { def partitionCount(p: T => Boolean): (Int,Int) = ... } 而不是这个你需要使用targetList.您不需要扩展List.在这个例子中,我创建了隐式使用的简单包装器MyRichList. 您可以通过为Traversable定义包装器来进一步概括包装器,以便它可以用于其他集合类型,而不仅仅用于列表: implicit def listToMyRichTraversable[T](l: Traversable[T]) = new MyRichTraversable(l) class MyRichTraversable[T](target: Traversable[T]) { def partitionCount(p: T => Boolean): (Int,Int) = ... } 另请注意,只有在范围内时才会使用隐式转换.这意味着,您需要导入它(除非您在已定义它的同一范围内使用它). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |