Scala 中的 Foreach 与 Map [英] Foreach vs Map in 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
})
其中 consumertxnlist 是 Seq[something] .
where consumertxnlist is a Seq[something] .
另一种方式是
var response = consumerTxnList._2.map(txData => RS_TxnNested(blabla))
有人可以帮助我澄清哪个更好以及为什么吗?
Can someone help me in clarifying which one is better and why?
推荐答案
正如您已经注意到的,Seq trait 中的 map 函数返回一个值.它的签名实际上是
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]
它旨在将函数应用于扩展 Seq 特征的集合的每个元素并返回一个新集合.
It is designed to apply a function to every element of a collection extending the Seq trait and return a new collection.
另一方面,foreach 具有相同的特征,具有以下签名:
On the other hand, foreach, in the same trait, has the following signature:
def foreach(f: (A) ⇒ 单位): 单位
这意味着它旨在执行具有副作用的函数.
This means that it's designed to execute functions with side-effects.
在您的示例中,您将值分配给响应"的操作视为副作用.如果您的实际目标是返回一个值(就像您想要做的那样),那么请使用 map.
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.
这篇关于Scala 中的 Foreach 与 Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!