Call By Value vs Call By Name
November 26, 2019 Leave a comment
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
Recent Comments