Scala: pass curried function as parameter

Is it possible to do something like the following?

def takeCurriedFnAsArg(f: (Int)(implicit MyClass) => Result) 
+6
source share
1 answer

Yes it is possible.

If you have a second parameter in curry marked implicit , the function seems not to be

 Int => (MyClass => Result) => ResultOfFunction 

which would be if the parameter of a cardinal function of a higher order was a regular parameter; instead, it looks like this:

 Int => ResultOfFunction 

Here is an example:

 scala> def curriedFn(i : Int)(implicit func : String => Int) : Boolean = (i + func("test!")) % 2 == 0 curriedFn: (i: Int)(implicit func: String => Int)Boolean scala> implicit val fn : String => Int = s => s.length fn: String => Int = <function1> scala> curriedFn _ res4: Int => Boolean = <function1> 

As you can see, the implicit parameter received "excluded". Why and how? This is a question for someone more knowledgeable than me. If I were to guess, I would say that the compiler directly replaces the parameter with an implicit value, but this can be very false.

In any case, deviations to the side, here is an example that is very relevant to your situation:

 scala> def foo(func : Int => Boolean) = if(func(3)) "True!" else "False!" foo: (func: Int => Boolean)String scala> foo(curriedFn) res2: String = True! 

Now, if the second parameter of the function was not implicit:

 scala> def curriedNonImplicit(i : Int)(fn : String => Int) : Boolean = (i + fn("test!")) % 2 == 0 curriedNonImplicit: (i: Int)(fn: String => Int)Boolean scala> curriedNonImplicit _ res5: Int => ((String => Int) => Boolean) = <function1> 

As you can see, the type of function is slightly different. This means that the solution will look different:

 scala> def baz(func : Int => (String => Int) => Boolean) = if(func(3)(s => s.length)) "True!" else "False!" baz: (func: Int => ((String => Int) => Boolean))String scala> baz(curriedNonImplicit) res6: String = True! 

You must specify the function directly inside the method, since it was not explicitly specified earlier.

+10
source

Source: https://habr.com/ru/post/956791/


All Articles