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)
     }
     calledByValue(System.nanoTime())

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)
     }
     calledByName(System.nanoTime())

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:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

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

Diabolical or Smart

Nitwit, Blubber, Oddment, Tweak !!

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com 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