By-name parameter vs anonymous function

Laziness is the same in the both cases, but there are slight differences. Consider:

def generateInt(): Int = { ... }
def byFunc(a: () => Int) { ... }
def byName(a: => Int) { ... }

// you can pass method without
// generating additional anonymous function
byFunc(generateInt)

// but both of the below are the same
// i.e. additional anonymous function is generated
byName(generateInt)
byName(() => generateInt())

Functions with call-by-name however is useful for making DSLs. For instance:

def measured(block: ⇒ Unit): Long = {
  val startTime = System.currentTimeMillis()
  block
  System.currentTimeMillis() - startTime
}

Long timeTaken = measured {
  // any code here you like to measure
  // written just as there were no "measured" around
}

Leave a Comment