scala - lambda function does not capture the surrounding variable
问题描述
f(code: String): String is the new code function, it takes one old code string and generates new 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
}
I passed the lambda function to get the new code and updated it to the newCodes array. The new code array shall be returned at the end of the function. But an empty array is returned.
Seems the lambda function is not captured the newCodes
variable, Why is that?
解决方案
Collecting the answers from the comments gives this solution:
def getNewCodes(oldCodes: Array[String]): Array[String] =
oldCodes.map(f)
In practice you would usually just write this in line and not bother with a separate method, especially as it is not clear where f
comes from.
推荐阅读
- linux - 防止性能名称破坏
- swagger - .NET Core Web API with Swagger:在同一个调用中同时发布文件和数据
- c++ - Q_PROPERTY 与私有二传手
- c - 与 Heisenbug 相反,仅在调试时出现分段错误,但程序运行正常
- javascript - 如果javascript中有超过2个,则拆分数据
- angular - Angular 8 / Typescript在调用数据时设置接口的属性
- spotify-scio - 如何处理自定义案例类的编码器
- math - 不使用 sqrt 计算二次方程的平方解
- excel - 无法将电子邮件移动到另一个文件夹错误 438 对象不支持此属性或方法
- google-chrome-extension - 安装后无法在 Edge 扩展中执行内容脚本