当前位置: 动力学知识库 > 问答 > 编程问答 >

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.

网友答案:

zipWithIndex will create a collection of 2-tuples. Creating your own will give you a little more flexibility in what type of data structure to use for the output.

But it's not called the Standard Library for nothing. Staying with established standards has many benefits: ease of code sharing, under-the-hood optimizations, ...

网友答案:

You can also use zip with stream to define your own indexes.

List("a", "b", "c") zip (Stream from 1)

It returns

List((a,1), (b,2), (c,3))

The above code returns a list formed from this list and collection[stream] by combining corresponding elements in pairs.

分享给朋友:
您可能感兴趣的文章:
随机阅读: