相关疑难解决方法(0)

使用方法丰富Scala集合

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

这是我到目前为止所能提出的:

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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这不起作用:

Vector(9, 11, 34).foreachWithIndex { (el, i) =>
  println(el, i)
}
Run Code Online (Sandbox Code Playgroud)

引发以下错误:

error: value foreachWithIndex is not a member of scala.collection.immutable.Vector[Int]
Vector(9, 11, 34).foreachWithIndex { (el, i) =>
Run Code Online (Sandbox Code Playgroud)

但是,当我明确应用转换方法时,代码可以正常工作:

iforeach[Int, Vector[Int]](Vector(9, 11, 34)).foreachWithIndex { (el, i) =>
  println(el, i) …
Run Code Online (Sandbox Code Playgroud)

scala implicit-conversion scala-collections enrich-my-library

4
推荐指数
1
解决办法
333
查看次数