J.Done J.Done - 6 months ago 37
Scala Question

Difference between .zipWithIndex and custom index value in Scala

val list = List("a", "b", "c")

If I would like to travel list's each element with index.
There is two way to do this.

first way that I made

var idx = 0
list.foreahch { str => ... idx++ }

another way from internet

list.zipWithIndex.foreach { case( str, idx) => ... }

What's difference between them?


Not a functional way to do it.

var index = 0

list.foreach { elem =>
 //do something with elem
 index += 1

In the above code following things are bad practices

1) mutable variable. (accidentally some one can mutate and not good in parallel & concurrent scenarios)

2) error prone. increment has to be done (if you forget incrementing thats a disaster)

Functional way

list.zipWithIndex.foreach { case (elem, index) =>
  //do something.

Index is magically given to the user. You do not have to worry about illegal accesses of the state, incrementing of index and is fool proof.