Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach vs Map in Scala [duplicate]

Tags:

scala

i tried two ways for making a list out of something

var response = List[RS_TxnNested]
consumertxnlist.foreach(txData => {
  response = RS_TxnNested(blabla) +: response
})

where consumertxnlist is a Seq[something] .

Another way is

var response = consumerTxnList._2.map(txData => RS_TxnNested(blabla))

Can someone help me in clarifying which one is better and why?

like image 943
legacy_shield Avatar asked Dec 03 '22 22:12

legacy_shield


2 Answers

As you've noticed already, the map function in the Seq trait returns a value. Its signature in fact is

def map[B](f: (A) ⇒ B): Seq[B]

It is designed to apply a function to every element of a collection extending the Seq trait and return a new collection.

On the other hand, foreach, in the same trait, has the following signature:

def foreach(f: (A) ⇒ Unit): Unit

This means that it's designed to execute functions with side-effects.

In your example, you're treating the operation of assigning the value to "response" as a side effect. If you're actual goal is to return a value (like it seems you want to do), then use map.

like image 109
DeusEx Avatar answered Dec 24 '22 12:12

DeusEx


The second version is more explicit in what it does.

map conveys a meaning of transforming something, which is exactly what you're doing.

foreach instead performs an operation on something outside its scope, which is not as clear.

In other words, when I read foreach I have to look at the whole scope, because I know you'll be performing a side effect (since foreach returns Unit)

When I read map I can confidently assume the only expression involved is the one I'm currently looking at.

map lowers the burden on the reader, and makes the code easier to reason about.

like image 33
Gabriele Petronella Avatar answered Dec 24 '22 12:12

Gabriele Petronella