7.4. Limitations

Closures have access to the lexical scope of their defining environment. Consider this example:

function plus_3 = {
  let foo = 3
  return |x| -> x + foo
}

The plus_3 function returns a closure that has access to the foo reference, just as you would expect. The foo reference is said to have been captured and made available in the closure.

It is important to note that captured references are constants within the closure. Consider the following example:

var a = 1
let f = {
  a = 2   # Compilation error!
}

The compilation fails because although a is declared using var in its original scope, it is actually passed as an argument to the f closure. Because function parameters are implicitly constant references, this results in a compilation error.

That being said, a closure has a reference on the same object as its defining environment, so a mutable object is a sensible way to pass data back from a closure as a side-effect, as in:

let list = java.util.LinkedList()
let pump_it = {
  list: add("I heard you say")
  list: add("Hey!")
  list: add("Hey!")
}
pump_it()
println(list)

which prints [I heard you say, Hey!, Hey!].