sasuke
sasuke

Reputation: 145

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?

Upvotes: 3

Views: 159

Answers (2)

chengpohi
chengpohi

Reputation: 14217

{
      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
  }

Upvotes: 3

sepp2k
sepp2k

Reputation: 370102

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.

Upvotes: 6

Related Questions