tags: programming-language scala functions function-calls

Call by value

  • By default parameters are passed to a function by call by value.
  • All the parameters are evaluated in the first place before passing to the function.
def add(x: Int, y: Int) = x + y
 
add(1, 2) // 3

Call by name

  • Parameters are not evaluated until the parameter is not referenced in the function application/body.
// with call by value.
def perform(work: Unit) = {
    println("Starting work!")
    println(work)
    println("Completed work!")
}
 
def job() = {
    println("Some job")
}
 
perform(job()) // will be evaluated then and there
//Some job
//Starting work!
//()
//Completed work!
// with call by name
def perform(work: => Unit) = {
    println("Starting work!")
    println(work)
    println("Completed work!")
}
 
def job() = {
    println("Some job")
}
 
perform(job()) 
//Starting work!
//Some job
//()
//Completed work!
  • job() is only evaluated once the parameter work is referenced.
  • The main disadvantage with call by name is that the parameter is evaluated every time when the parameter is referenced.