通过一种方法丰富Scala集合 [英] Enriching Scala collections with a method
本文介绍了通过一种方法丰富Scala集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Scala集合上添加foreachWithIndex
方法?
How do I add a foreachWithIndex
method on Scala collections?
这是到目前为止我能想到的:
This is what I could come up with so far:
implicit def iforeach[A, CC <: TraversableLike[A, CC]](coll: CC) = new {
def foreachWithIndex[B](f: (A, Int) => B): Unit = {
var i = 0
for (c <- coll) {
f(c, i)
i += 1
}
}
}
这不起作用:
Vector(9, 11, 34).foreachWithIndex { (el, i) =>
println(el, i)
}
引发以下错误:
error: value foreachWithIndex is not a member of scala.collection.immutable.Vector[Int]
Vector(9, 11, 34).foreachWithIndex { (el, i) =>
但是,当我明确应用转换方法时,代码将起作用:
However the code works when I explicitly apply the conversion method:
iforeach[Int, Vector[Int]](Vector(9, 11, 34)).foreachWithIndex { (el, i) =>
println(el, i)
}
输出:
(9,0)
(11,1)
(34,2)
如何在不显式应用转换方法的情况下使其工作?谢谢.
How do I make it make it work without explicit application of a conversion method? Thanks.
推荐答案
您需要扩展Iterable:
You need to extend Iterable:
class RichIter[A, C](coll: C)(implicit i2ri: C => Iterable[A]) {
def foreachWithIndex[B](f: (A, Int) => B): Unit = {
var i = 0
for (c <- coll) {
f(c, i)
i += 1
}
}
}
implicit def iter2RichIter[A, C[A]](ca: C[A])(
implicit i2ri: C[A] => Iterable[A]
): RichIter[A, C[A]] = new RichIter[A, C[A]](ca)(i2ri)
Vector(9, 11, 34) foreachWithIndex {
(el, i) => println(el, i)
}
输出:
(9,0)
(11,1)
(34,2)
请参阅 Rex的这篇文章克尔以获取更多信息.
See this post by Rex Kerr for more information.
这篇关于通过一种方法丰富Scala集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文