8.7. Closures

Given a closure reference or a method handle, one can convert it to an instance of an interface with a single method declaration, as in:

local function listener = |handler| -> asInterfaceInstance(ActionListener.class, handler)

# (...)
let button = JButton("Click me!")
button: addActionListener(listener(|event| -> println("Clicked!")))

It is possible to test if an object is a closure or not with the isClosure function. This is useful to support values and delayed evaluation, as in:

if isClosure(value) {
  map: put(key, value())
} else {
  map: put(key, value)
}

You can get a reference to a closure using the predefined fun function:

import golotest.Closures

local function local_fun = |x| -> x + 1

function call_local_fun = {
  let f = fun("local_fun", golotest.Closures.module)
  return f(1)
}

Because functions may be overloaded, there is a form that accepts an extra parameter for specifying the number of parameters:

import golotest.Closures

local function local_fun = |x| -> x + 1

function call_local_fun = {
  let f = fun("local_fun", golotest.Closures.module, 1)
  return f(1)
}