简体   繁体   中英

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?

What distinguishes by-name parameters from normal ones is that the argument expression is evaluated whenever the parameter is used. So if you use it twice, the expression is evaluated twice. And if you don't use it at all, it's never evaluated.

So in your case "Hello Back" is not printed because you never use y .

Also is the function/object ;whose body is the instruction println("Hello Back"); stored somewhere on the heap?

The generated code for by-name parameters is the same as for functions, so it will create a function object on the heap.

{
      println("Hello Back")
}

this is a code block , 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
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM