scalaparameterslazy-evaluationcallbyname

call-by-name and call-by-value with lazy val


I would like to know the difference between a variable passed by value, but lazy, and pass a variable by name in Scala.

I wrote this example to try to show but I do not, how should I do?

def callByValue(x : Unit) = {
x
x
}

def callByName(x : => Unit) = {
    x
    x
}

lazy val j = {println("initializing lazy"); 0}
var i = {println("initializing"); 0}

callByName(i = i + 1)
print(i + "\n")  // "5"

callByValue(j)
print(j + "\n")  // "1"

Solution

  • By "5" you mean, like, 2, right? And "1" means 0?

    Is this one of those Google interview questions?

    This shows the closure evaluated twice by the function:

    scala> callByName {
         | println("calling")
         | i += 1
         | }
    calling
    calling
    

    and then

    scala> println(i)
    4
    

    That's after it was 2.

    HTH.