Higher-order Functions in Scala

Apart from objects and primitives, Scala allows to pass functions also as parameters to other functions. Such functions which takes other function(s) or return another function is called Higher-order Function.

Syntax of a function taking another function is

def higherOrderFunction ( inputFn: {functionArgs}=>{returnType}, ... )

Lets see a real example of an Higher-order function

def log(message: String, fn: String => Unit = Logger.logWarning){

The log() function takes a message & a function and just invokes it with the message. The function can be anything which takes a “String” and returns nothing (Unit – similar to void in Java). Note that as described in my previous post¬†you can provide a default value for the function parameters as well.

Now the callers can invoke log() with a message and optionally a function which should be used to log the message. If no function is provided as second argument the message will be logged using Logger.logWarning, which is provided as the default value.

object Logger {
  def logError(msg: String) {
    println("ERR : " + msg)

  def logWarning(msg: String) {
    println("WARN: " + msg)
log("some warning")
log("some error", Logger.logError)

For the complete source code, click here


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s