sasuke sasuke - 15 days ago 8
Scala Question

Understanding Call-By-Name in Scala

I am new to scala language, therefore I will be grateful if someone could explain me this code-snippet :

object C {

def main(args: Array[String]) = {
measure("Scala"){
println("Hello Back")
}
}

def measure(x: String)(y: => Unit){
println("Hello World " + x)
}
}


Console output :

Hello World Scala


My question is why the program didn't print
Hello Back
as well? Also is the function/object ;whose body is the instruction
println("Hello Back")
; stored somewhere on the heap?

Answer
{
      println("Hello Back")
}

this is a method, equal to:

def f = {println("Hello World")}
measure("Scala")(f)

so for measure method, you need to explicitly call:

  def measure(x: String)(y: => Unit){
   println("Hello World " + x)
   y
  }