Search code examples
scalaanonymous-functionlazy-evaluationcallbynamecall-by-value

In Scala, when would be a good time to use lazily evaluated parameter rather than to use a function as a parameter?


def getStr(): String = {
  println("getStr is running")
  "str"
}

def lazyHello(para: => String) = {
  println("lazy hello is runing")
  println(para)
}

def notLazyHello(para: String) = {
  println("not lazy hello is runing")
  println(para)
}

def anoyHello(para: () => String) = {
  println("anoy hello is runing")
  println(para())
}

notLazyHello(getStr)
lazyHello(getStr)
anoyHello(getStr)

got this result:

scala> notLazyHello(getStr)
getStr is running
not lazy hello is runing
str

scala>     lazyHello(getStr)
lazy hello is runing
getStr is running
str

scala>     anoyHello(getStr)
anoy hello is runing
getStr is running
str

seems like lazyHello and anoyHello perform the same.

So, in Scala, when would be a good time to use lazily evaluated parameter rather than to use a function as a parameter?


Solution

  • Your observation is correct. lazyHello and anoyHello are in fact the same. This is because para: => String is shorthand for para: () => String.

    Another way to look at this:

    () => String is a function that takes no parameters and returns a string.

    => String is something that evaluates to a string, without taking parameters. So essentially call-by-name is a function without an input parameter.