7.5. Closures to single-method interfaces

The Java SE APIs have plenty of interfaces with a single method: java.util.concurrent.Callable, java.lang.Runnable, javax.swing.ActionListener, etc.

The predefined function asInterfaceInstance can be used to convert a method handle or Golo closure to an instance of a specific interface.

Here is how one could pass an action listener to a javax.swing.JButton:

let button = JButton("Click me!")
let handler = |event| -> println("Clicked!")
button: addActionListener(asInterfaceInstance(ActionListener.class, handler))

Because the asInterfaceInstance call consumes some readability budget, you may refactor it with a local function as in:

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

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

Here is another example that uses the java.util.concurrent APIs to obtain an executor, pass it a task, fetch the result with a Future object then shut it down:

function give_me_hey = {
  let executor = Executors.newSingleThreadExecutor()
  let future = executor: submit(asInterfaceInstance(Callable.class, -> "hey!"))
  let result = future: get()
  executor: shutdown()
  return result
}