Call by Value, Name, Need
Call by
- value
- name
- need
Call by Value
Evaluated on function call
def functionByValue(x: Long) =
println(x)
println(x)
The param x is evaluated on the function call
From then on the value of x is fixed
So the two print statements will print the same value
Call by Name
Evaluated on usage of x
def functionByName(x: => Long) =
println(x)
println(x)
The param x is evaluated on the moment of usage
So the two print statements will print the different values
Call by Need
Evaluated on the first time usage of x1
def functionByNeed(x: => Long) = {
lazy val x1 = x
println(x1)
println(x1)
The param x is evaluated on the first println usage
From then on the value of lazy x1 is fixed
So the two print statements will print the same value
main
def main(args: Array[String]): Unit =
functionByValue(System.nanoTime())
functionByName(System.nanoTime())
functionByNeed(System.nanoTime())
// 118920267089041
// 118920267089041
// 118920327472000
// 118920327493583
// 118920327830750
// 118920327830750