Scala, Currying for a method with several parameters, including implicit parameters?

After discovering that the currying multi parameter-groups method is possible , I try to get a partially applied function that requires implicit parameters.

This is impossible to do. If you could not explain to 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 am using a singleton object to create this partially applied function, and I want to use it in the area where the implicit int is defined.

+7
source share
2 answers

This is because you do not have an implicit Int. Cm:

 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 result is replaced by the real value by the compiler. If you feed a method, the result is a function, and functions cannot have implicit parameters, so the compiler must insert the value at the moment you feed the method.

edit:

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

 object Foo { def partialSum(implicit x: Int) = sum(3)(x) } 
+8
source
 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 
0
source

All Articles