【问题标题】:lambda function does not capture the surrounding variablelambda 函数不捕获周围的变量
【发布时间】: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

标签: scala lambda


【解决方案1】:

从 cmets 收集答案给出了这个解决方案:

def getNewCodes(oldCodes: Array[String]): Array[String] =
  oldCodes.map(f)

在实践中,您通常会直接将其写成一行,而不是使用单独的方法,尤其是因为尚不清楚 f 的来源。

【讨论】:

    猜你喜欢
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2011-11-05
    相关资源
    最近更新 更多