Get index of current element in a foreach method of Traversable?

前端 未结 4 801
南笙
南笙 2020-12-07 18:49

Suppose I have two arrays:

val ar1 = Array[String](\"1\", \"2\", \"3\")
val ar2 = Array[String](\"1\", \"2\", \"3\", \"4\")

Now for each e

4条回答
  •  囚心锁ツ
    2020-12-07 19:18

    This is how you loop with an index in idiomatic Scala:

    scala> List("A", "B", "C").zipWithIndex foreach { case(el, i) =>
         |   println(i + ": " + el)
         | }
    0: A
    1: B
    2: C
    

    And here is the idiomatic Scala way to do what you are trying to achieve in your code:

    scala> val arr1 = Array("1", "2", "3")
    arr1: Array[java.lang.String] = Array(1, 2, 3)
    
    scala> val arr2 = Array("1", "2", "3", "4")
    arr2: Array[java.lang.String] = Array(1, 2, 3, 4)
    
    scala> (arr1, arr2).zipped.map(_ + _) foreach println
    11
    22
    33
    

提交回复
热议问题