Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

currying

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.

like image 559
kheraud Avatar asked Jun 04 '12 12:06

kheraud


1 Answers

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)
}
like image 182
drexin Avatar answered Sep 19 '22 06:09

drexin