Passing a block of code to a function in Scala (callbacks)

I've posted a lot of Scala source code examples out here lately, and as I keep trying to learn more about passing one function to another function in Scala (function callbacks), here's another example showing how you can use Scala's functional programming approach to clean up some Java Swing code:

// a function that takes a function as an argument
def invokeLater(callback: => Unit) {
  SwingUtilities.invokeLater(new Runnable() {
    def run() {

// create function literals using the above function
def updateUISarahIsSleeping = invokeLater(microphonePanel.setSarahIsSleeping)
def updateUISarahIsSpeaking = invokeLater(microphonePanel.setSarahIsSpeaking)
def updateUISarahIsListening = invokeLater(microphonePanel.setSarahIsListening)
def updateUISarahIsNotListening = invokeLater(microphonePanel.setSarahIsNotListening)

// note: "microphonePanel.setSarahIsSleeping" and those other microphonePanel
// arguments are also functions

As you can see from that code, in Scala I can just create an invokeLater function one time, and then I can just pass that function another function every time I want to run the SwingUtilities invokeLater Runnable code. The four lines at the bottom of that example are all examples of function literals in Scala, meaning that in other places in my code, I can invoke them like this:


As the function name implies, this function call updates the SARAH user interface to show that SARAH is currently listening to the user.

Aside: What is SARAH?

As for what SARAH is, here's SARAH in action:

As you can see, SARAH is a voice/speech interaction application that I've written for Mac OS X computers. It's free, open source, and written in Scala.

This website is a little one-man operation. If you found this information helpful, I’d appreciate it if you would share it.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.