Call-by-name in Scala

Call-by-name is where a parameter to a function is a function evaluated each time it is used. In this example the function getString is invoked each time it is accessed by the logWaitThenLogAgain method:

import java.util.Date

/**
 * This class demonstrates Call-By-Name behaviour in Scala.
 */
object CallByName extends App {

  /**
   * Note the param of this function:
   * f: => String, instead of f:String
   * This makes the function 'f' a call-by-name parameter 
   * evaluated every time 'f' is accessed.
   */
  def logWaitThenLogAgain(f: => String) = {
    println("[INFO] " + f)
    Thread.sleep(1000) // wait 1 second
    println("[INFO] " + f)
  }

  // Just returns the current date/time as a String
  def getString = new Date().toGMTString()

  // Call our function passing the getString method.
  logWaitThenLogAgain(getString)
}

output:

[INFO] 25 Sep 2013 18:21:26 GMT
[INFO] 25 Sep 2013 18:21:27 GMT

The example demonstrates how Scala passes a method parameter as a function.

Advertisements

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