Call By Value vs Call By Name

Call By Value is just like any other programming language where we use the static value of the argument directly

     def calledByValue(x: Long): Unit = {
         println("by value: " + x)
         println("by value: " + x)

Call By Name
Here instead of the value, the expression is passed as is and it will be evaluated by the compiler everytime. Call by Name is lazily evaluated.

     def calledByName(x: => Long): Unit = {
         // the arrow above is going to tell the compiler to evaluate the parameter by NAME
         // x is evaluated for every use
         println("by name: " + x)
         println("by name: " + x)

Lazy Evaluation example

def infinite(): Int = 1 + infinite()
def printFirst(x: Int, y: => Int) = println(x)

// println(infinite(), 34) // errors with stackoverflow

println(34, infinite()) // runs fine as second parameter is lazily evaluated and is never executed

Leave a Reply

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

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

Facebook photo

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

Connecting to %s


Mostly technology with occasional sprinkling of other random thoughts


Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates


A topnotch site


Just another site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: