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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With