scala - 使用方法丰富 Scala 集合

标签 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
    }
  }
}

这不起作用:
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) =>

但是,当我明确应用转换方法时,代码有效:
iforeach[Int, Vector[Int]](Vector(9, 11, 34)).foreachWithIndex { (el, i) =>
  println(el, i)
}

输出:
(9,0)
(11,1)
(34,2)

如何在不显式应用转换方法的情况下使其工作?谢谢。

最佳答案

您需要扩展 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)

有关更多信息,请参阅 this post by Rex Kerr

关于scala - 使用方法丰富 Scala 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6823213/

相关文章:

scala - 抽象案例类

c++ - 函数参数到子类c++的转换

scala - 如何在Scala中的过滤器, map ,flatMap期间轻松地从一种集合类型转换为另一种集合类型?

c++ - 是否可以通过列表初始化调用用户定义的转换函数?

java - Java 与 Scala 集成 : Extending from Scala classes

scala - 由 : java. lang.ClassNotFoundException : org. apache.hadoop.hbase.HBaseConfiguration 引起

java - 如何在Scala中重写Java的ArrayList的addAll(Collection<? extends E> c)方法?天真的方法无法编译

java - 为什么 List<Object[]> 需要显式转换才能转换为 Scala 集合?

scala - 使用并行集合时,批量执行哪些操作?奇怪的行为在这里

scala - 如何在 Scala 中定义自定义集合接口(interface)而不定义实现?