使用方法丰富Scala集合

使用方法丰富Scala集合,scala,implicit-conversion,scala-collections,enrich-my-library,Scala,Implicit Conversion,Scala Collections,Enrich My Library,如何在Scala集合上添加foreachWithIndex方法 这就是我目前能想到的: 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 }

如何在Scala集合上添加
foreachWithIndex
方法

这就是我目前能想到的:

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
    }
  }
}
引发以下错误:

error: value foreachWithIndex is not a member of scala.collection.immutable.Vector[Int]
Vector(9, 11, 34).foreachWithIndex { (el, i) =>
但是,当我显式应用转换方法时,代码可以工作:

iforeach[Int, Vector[Int]](Vector(9, 11, 34)).foreachWithIndex { (el, i) =>
  println(el, i)
}
输出:

(9,0)
(11,1)
(34,2)

我如何使它在没有显式应用转换方法的情况下工作?谢谢。

简单的回答是,如果这样做,您必须参数化
CC
,否则类型推断器无法确定
A
是什么。另一个简短的回答是按照我在回答中描述的方式去做


要进一步扩展,实际上没有理由需要
CC扩展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)
}

有关更多信息,请参阅。

如果您感兴趣的只是使用索引进行迭代,那么您最好跳过整个PIMP部分,然后执行以下操作

coll.zipWithIndex.foreach { case (elem, index) =>
  /* ... */
}

实际上,这只是我试图实现的一组额外方法中的一个方法。其他一些方法需要构造相同类型的新集合。那么
mapWithIndex
呢?这个名单还有很多。
(9,0)
(11,1)
(34,2)
coll.zipWithIndex.foreach { case (elem, index) =>
  /* ... */
}