Abhishek kapoor
Abhishek kapoor

Reputation: 151

Call by name in scala

Are both greet method same

object test {
  def greet = { println("hi")}                    //> greet: => Unit
  def greet1(f: => Unit)= {println("hi")}         //> greet1: (f: => Unit)Unit
}

As per my understand greet is a function which does not take any argument and return Unit and arguments are call by name. And greet1 is a function which takes function which returns Unit and is also a call by name for its parameters. Am confused, could anyone be kind enough to explain the difference.

Upvotes: 0

Views: 125

Answers (1)

Rich Oliver
Rich Oliver

Reputation: 6119

greet is a a method that returns unit. In this particular case they do functionally the same thing. greet1 takes a function returning Unit as a parameter but does not use it. so you could call greet1 as:

greet1(greet)

And as greet is passed by parameter it would not be applied. But generally they are not the same thing. If you changed greet1 to the following:

def greet1(f: => Unit)= {
  println("hi")
  f()
}

calling greet1 as above would print "hi" twice. Or

def greet1(f: => Unit)= {
  println("hi")
  f()
  f()
}

Would print "hi" three times. As the parameter is evaluated every time the parameter is called. If you were to rewrite greet1 as:

def greet1(f: Unit)= {
  println("hi")
  f
  f
} // and call it:

greet1(greet)

It would only print "hi" twice as the parameter is call by value it is evaluated once and only once when called.

Upvotes: 5

Related Questions