According to my understanding randList
is definitely not a closure (Wikipedia seems to agree) , since - in the snippet of code you provided - it only depends on local variables (parameters are also considered local variables). Considering the body of randList
, there is no so-called free variable, i.e., a variable that does not get its value from the current lexical scope, where the latter is the method body itself. len
and n
are both variables of the current lexical scope since they are both parameters of the enclosing definition of randList
.
Consider this example:
var n = 10
val f = (x: Int) => x + n
println(f(1)) // 11
n = 20
println(f(1)) // 21
The function f
is a closure because it does not only depend on its parameters, but also on a variable that is declared outside of its own lexical scope (namely n
).
The Wikipedia article mentions that a closure is defined by a function together with a lexical scope that declares the free arguments. The next example illustrates this:
// n == 20
// f as above
def foo(g: Int => Int) = {
val n = 100
g(1)
}
println(foo(f)) // 21
The result of foo(f)
is still 21
although foo
defines its own local variable n
, and one might assume that f
now uses this n
. However, the closure f
is coupled to the lexical scope that surrounds its declarations, which is where the value of n
is take from when f
is evaluated.