Scala 趣题 20


package pzs

object Pz020 extends App {
  var x = 0
  def counter = { x += 1; x }
  def add(a: Int)(b: Int) = a + b
  val adder1 = add(counter)(_)
  val adder2 = add(counter) _
  println("x = " + x)
  println(adder1(10))
  println("x = " + x)
  println(adder2(10))
  println("x = " + x)
}















解释


Explanation


f(a) _ and f(a)(_) have different meanings, governed by different sections of the Scala language specification.


f(a)(_) is the placeholder syntax for anonymous functions, described in SLS §6.23. Evaluation is deferred.


f(a) _ is eta expansion, described in SLS §6.26.5. Arguments given are evaluated eagerly; only the method call itself is deferred.


In this example, the eta expansion in


val adder2 = add(counter) _


causes eager evaluation, as described: as soon as that line is run, Scala actually evaluates counter and binds 1, the result, to the counter argument for adder2. Hence x is 1 when first printed.


adder1, on the other hand, is an anonymous function, so its counter argument is only bound when adder1 is evaluated. Since x is already 1 at this point, counter will be 2 and the evaluation of adder1 prints 12. The value of x is now 2, as indicated by the program's output.


你可能感兴趣的:(scala)