【问题标题】:Enriching Scala collections with a method使用方法丰富 Scala 集合
【发布时间】:2011-10-12 23:39:54
【问题描述】:

如何在 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)

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

【问题讨论】:

    标签: scala implicit-conversion scala-collections enrich-my-library


    【解决方案1】:

    如果您感兴趣的只是使用索引进行迭代,您不妨跳过整个拉皮条部分并执行类似的操作

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

    【讨论】:

    • 那么mapWithIndex 怎么样?名单还在继续。
    【解决方案2】:

    简短的回答是,如果您这样做,则必须参数化 CC,否则类型推断器无法弄清楚 A 是什么。另一个简短的答案是按照我在this question 的答案中描述的方式进行操作。

    为了进一步扩展,确实没有理由需要CC &lt;: TraversableLike--只需使用Traversable 并以iforeach[A](coll: Traversable[A]) 开头!您不需要使用花哨的类型边界来使用超类/超特征。如果您想做一些更复杂的事情,即返回另一个保留集合类型的集合,那么您需要使用构建器等,我在另一个问题中对此进行了描述。

    【讨论】:

    • 实际上,这只是我尝试实现的一组额外方法中的一种方法。其中一些其他方法需要构造一个相同类型的新集合。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 2011-02-11
      相关资源
      最近更新 更多