[SOLVED] Difference between (a: Int) and (a: => Int) in argument of method

I found methods can take argments as =>: T type, but I don’t know any advantage to using it instead of using T type.

I’m glad if someone tells me the difference.

Example:

def func1(a: Int): Unit = {
    println(a)
}

def func2(a: => Int): Unit = {
    println(a)
}

It’s call by value and call by name
There have different evaluation strategies, that’s to say , “evaluate value at once” vs “evaluate value each time invoked”
for example

scala> def something() = {
     |   println("calling something")
     |   1 // return value
     | }
something: ()Int

scala> def callByValue(x: Int) = {
     |   println("x1=" + x)
     |   println("x2=" + x)
     | }
callByValue: (x: Int)Unit

scala> 

scala> def callByName(x: => Int) = {
     |   println("x1=" + x)
     |   println("x2=" + x)
     | }
callByName: (x: => Int)Unit

scala> callByValue(something())
calling something
x1=1
x2=1

scala> callByName(something())
calling something
x1=1
calling something
x2=1

see the doc : https://docs.scala-lang.org/tour/by-name-parameters.html

2 Likes

@counter already did a great job explaining what they are, but you may still be wondering why are they useful.

The most common use case for them is when you do not always need that value, for example the method getOrElse on the Option class is by-name. As such, you can write code like this:

def getUserById(id: Id): User =
  cache
    .get(key = Id) // This returns an Option[User]
    .getOrElse(expensiveFetchFromDb())

This code will only call the expensive operation if it is needed.

2 Likes

@counter @BalmungSan
Both answers really make sense to me.
Thanks a lot!

see also https://docs.scala-lang.org/tour/by-name-parameters.html

1 Like

see also https://www.slideshare.net/pjschwarz/non-strict-functions-bottom-and-scala-byname-parameters