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?

1 Answers

4
Tim On Best Solutions

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.