Scala 趣题 17 隐式参数和偏函数

输出是多少? 

  implicit val z1 = 2
  def addTo(n: Int) = {
    def add(x: Int)(y: Int)(implicit z: Int) = x + y + z
    add(n) _
  }
  
  val addTo1 = addTo(1)
 println( addTo1(2))



原题为


implicit val z1 = 2
def addTo(n: Int) = {
   def add(x: Int)(y: Int)(implicit z: Int) = x + y + z
   add(n) _  // 这里报错
}

implicit val z2 = 3
val addTo1 = addTo(1)
addTo1(2)
addTo1(2)(3)

但是在2.11.2下报错,原题的编译环境是2.10.0


改为

  implicit val z1 = 2
  def addTo(n: Int) = {
    def add(x: Int)(y: Int)(implicit z: Int) = x + y + z
    add(n)(_: Int)(3)
  }

  implicit val z2 = 3
  val addTo1 = addTo(1)
  addTo1(2)
  addTo1(2)(3)  // 这里报错,不需要参数3



作者对于原题的解释是:

Explanation


When eta expansion is applied to method add, the result is a function of type Int => Int, i.e. the implicit parameters are resolved before eta expansion is applied. Therefore the implicit value z1 = 2 is used as value for the implicit parameter z.


If no implicit parameter were available, the compiler would issue an error message:


scala> def add(x: Int)(y: Int)(implicit z: Int) = x + y + z

add: (x: Int)(y: Int)(implicit z: Int)Int


scala> add(1) _

:9: error: could not find implicit value for parameter z: Int

              add(1) _

                 ^


One could also specify an explicit value for z if no implicit value is defined in the current context, but then the type has to be specified on the placeholder.


scala> val addTo1And3 = add(1)(_: Int)(3)

addTo1And3: Int => Int = 


This explains the result, i.e. the invocation of addTo1(2) returns 5 (1 + <param> + 2) and addTo1(2)(3) fails to compile as on the object 5 (result of addTo1(2)) no method apply is defined.


scala> addTo1(2)(3)

:10: error: Int does not take parameters

              addTo1(2)(3)

                       ^










你可能感兴趣的:(scala)