Scala: pass-by-value vs pass-by-name

pass-by-value: expressions as arguments to a function are evaluated once on passing to the function

pass-by-name: expressions are evaluated only when referenced, if they are not referenced they are not evaluated, and the expression is evaluated every time the expression is referenced

System.out.println("Calling squareCallByValue(): ")
squareCallByValue( doSomething() )

System.out.println("nCalling squareCallByName(): ")
squareCallByName( doSomething() )

System.out.println("nCalling callByNameNoReference(): ")
callByNameNoReference( doSomething() )
def doSomething() : Int = {
    System.out.println("doSomething() called")

    2
  }

  def squareCallByName(x: => Int) = {
    var result = x * x
    System.out.println("x in squareCallByName: " + result)
  }

  def callByNameNoReference(x: => Int) = {
  }

  def squareCallByValue(x: Int) = {
    var result = x * x
    System.out.println("x in squareCallByValue: " + result)
  }

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.