Scala 趣题 18 偏函数对默认参数的影响


下面程序结果会是什么?


package pzs

object Pz018 extends App {
  def invert(v3: Int)(v2: Int = 2, v1: Int = 1) {
    println(v1 + ", " + v2 + ", " + v3);
  }
  def invert3 = invert(3) _

  invert3(v1 = 2)
  invert3(v1 = 2, v2 = 1)

}















解释

eta展开,丢失了默认参数的信息


Explanation


The type of invert3 after eta-expansion (SLS §6.26.5) is no longer a method but a function object, i.e. an instance of Function2[Int, Int, Unit]. This is also reported by the REPL:


scala> def invert3 = invert(3) _

invert3: (Int, Int) => Unit


This function object has an apply method (inherited from Function2[T1, T2, R]) with the following signature:


  def apply(v1: T1, v2: T2): R


In particular, this method defines no default values for its arguments! As a consequence, invert3(v1 = 2) leads to a compile time error (as there are not enough actual arguments for method apply).


The argument names v1 and v2 are the names as they are defined in the apply-method of Function2[T1, T2, R]. The argument names of apply-method of every function with two arguments are named v1 and v2, in particular these names are by no means related to the argument names of method invert3. Method invert3 has by chance arguments with the same names, but unfortunately in a different order. invert3(v1 = 2, v2 = 1) prints 1, 2, 3 as the parameter v1 (which corresponds to the parameter v2 in method invert) is set to 2 and parameter v2 (which corresponds to the parameter v1 in method invert) is set to 1.


你可能感兴趣的:(scala)