Gary Sieling

Scala zipWithIndex example

If you’re new to Scala, the idea of immutable data structures can be a pain at times, especially when you need to replace “for (int x=0; x < arr1.length; x++)". One easy way to handle this is zipWithIndex:

val arr1 = List(“a”, “b”, “c”)

arr1.zipWithIndex

Note that you call this WITHOUT the parens:

res14: List[(String, Int)] = List((a,0), (b,1), (c,2))

Otherwise, you’ll get an awful type error, which indicates you probably weren’t doing what you wanted:

:9: error: not enough arguments 
for method zipWithIndex: 
(implicit bf: scala.collection.generic.CanBuildFrom
[List[String],(A1, Int),That])That.
Unspecified value parameter bf.

Using the above technique, you get a new list, with tuples of object + index. If you need something that doesn’t pre-compute everything, like your old “for” loop, you can do something like this:

arr1
  .view
  .zipWithIndex
  .flatMap(
    x => { 
      System.out.println(x); 
      None 
    }).toList
(a,0)
(b,1)
(c,2)
res49: List[Nothing] = List()
Exit mobile version