Omgo's Blog

June 7, 2010

scala call-by-name (=>) vs call-by-type

Filed under: scala — aswin @ 9:43 pm

Scala has lot of small surprises and this is one such thing

Given the following

  def byName(a: => Unit) = {
    for (i <- 0 until 10) {println(a)}


  def byValue(a: Unit) = {
    for (i <- 0 until 10) {println(a)}


  var i = 1;

  byValue(i = i + 1)

  byName(i = i + 1)

This would print 2 followed by 12. What is happening here is that in case of byName the evaluation of the arguments happens after the the byName method itself is invoked and the evaluation happens everytime the method parameter “a” is used within the body on the byName method. Since the parameter “a” is refereed in the loop of 10, it executes the statement “i = i +1” 10 times yeielding the result of 12.
In case of byValue (the default invocation mechanism in scala and also in java) the statements in parameter position is evaluated before the actual method call and only the result is passed to the method and hence the evaluation happens only once.
Pretty important difference as this could lead to unintended behavior if not careful. BTW the way create a byName call is having the “=>” between the parameter and the returntype in the argument list “byName(a: => Unit)”

References,%202009-11-09,%2017:29/named-args.pdf (named args and such)

The named arg feature introduced in 2.8 :,%202009-11-09,%2017:29/named-args.pdf


Blog at