【发布时间】:2019-05-13 23:07:46
【问题描述】:
f(code: String): String是新的code函数,它取一个旧的code string,生成新的code string。
def getNewCodes(oldCodes: Array[String]): Array[String] = {
val newCodes: Array[String] = Array()
oldCodes.foreach(code => newCodes :+ f(code)) // newCodes is not captured by the lambda function
newCodes // returns the empty array
}
我通过 lambda 函数来获取新代码并将其更新到 newCodes 数组。新的代码数组应在函数结束时返回。但返回的是一个空数组。
似乎lambda函数没有捕获newCodes变量,这是为什么呢?
【问题讨论】:
-
因为
:+返回了数组的新副本,并附加了元素。它不会改变原始数组。 -
另外,
newCodes.forEach(...)不会对空数组执行任何操作。也许你的意思是oldCodes.forEach(...)? -
@marstran 我想我应该为 Scala 数组寻找某种更新函数
-
我认为你可以这样做
val newCodes = oldCodes.map(code => f(code)) -
甚至
val newCodes = oldCodes map f