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)
  println(i);

  byName(i = i + 1)
  println(i)

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
http://scala.sygneca.com/faqs/language#what-s-the-difference-between-a-lazy-argument-a-no-arg-function-argument-and-a-lazy-value
http://www.scala-lang.org/sites/default/files/sids/rytz/Mon,%202009-11-09,%2017:29/named-args.pdf (named args and such)

The named arg feature introduced in 2.8 : http://www.scala-lang.org/sites/default/files/sids/rytz/Mon,%202009-11-09,%2017:29/named-args.pdf

2 Comments »

  1. […] returning a value of type A, into a function which evaluates the expression when called (using scala call-by-name syntax). This allows us to rewrite the initial example […]

    Pingback by Lazy parallel evaluation « Paradigmatic's — March 6, 2011 @ 3:25 pm

  2. Great article! This helped me far more than other documentation I’ve read.

    Comment by RJP — September 29, 2012 @ 3:56 am


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.