Scala, Currying on multi parameter-group method including implicit params?

柔情痞子 提交于 2019-12-22 04:45:23

问题


After having discovered that currying multi parameter-groups method is possible, I am trying to get a partially applied function which requires implicit parameters.

It seams not possible to do so. If not could you explain me why ?

scala> def sum(a: Int)(implicit b: Int): Int = { a+b }
sum: (a: Int)(implicit b: Int)Int

scala> sum(3)(4)
res12: Int = 7

scala> val partFunc2 = sum _
<console>:8: error: could not find implicit value for parameter b: Int
       val partFunc2 = sum _
                       ^

I use a singleton object to create this partially applied function and I want to use it in a scope where the implicit int is defined.


回答1:


That is because you don't have an implicit Int in scope. See:

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

scala> foo _
<console>:9: error: could not find implicit value for parameter y: Int
              foo _
              ^

scala> implicit val b = 2
b: Int = 2

scala> foo _
res1: Int => Int = <function1>

The implicit gets replaced with a real value by the compiler. If you curry the method the result is a function and functions can't have implicit parameters, so the compiler has to insert the value at the time you curry the method.

edit:

For your use case, why don't you try something like:

object Foo {
  def partialSum(implicit x: Int) = sum(3)(x)
}



回答2:


scala> object MySingleton {
 |   def sum(a: Int)(implicit b: Int): Int = { a+b }
 |  
 |
 |   def caller(a: Int) =  {
 |     implicit val b = 3; // This allows you to define the partial below
 |     def pf = sum _      // and call sum()() without repeating the arg list. 
 |     pf.apply(a)
 |   }
 | } 
defined module MySingleton


scala> MySingleton.caller(10)
res10: Int = 13


来源:https://stackoverflow.com/questions/10881340/scala-currying-on-multi-parameter-group-method-including-implicit-params

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!