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() { callback } }); } // 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:
updateUISarahIsListening
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 post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |