Function Type with Implicit Parameters in Scala

I would like to have a higher order function that takes a parameter - a function that takes a specific implicit parameter.

To be more precise, I'm trying to create a function that accepts a Future creation method that depends on an implicit context and returns a method that does not depend on the context.

To be more specific, let's say that I have something like this:

 def foo(a: Int)(implicit ctx: ExecutionContext): Future[Float] = future { somelongBar... } 

I would like to have a method like this:

 def provideCtx[A](func: ExecutionContext => A): A = { val ctx = setupCtx func(ctx) } 

but if I call provideCtx(foo) , the compiler complains about the lack of a hidden execution context.

The fact that I'm dealing with an ExecutionContext is not very important. I would like to find how to write a parameter type to accept a function with an implicit argument of a specific type. I understand that the implicit part is a curryed argument, so I actually have a function like this: ExecutionContext => Int => Future[Float] , and I'm sure that at runtime jvm doesn't know that ExecutionContext is implicit, but I can 'make the compiler understand this.

+7
scala implicit currying higher-order-functions
source share
1 answer

The problem is that foo is a method, not a function, and eta-expand (which converts methods to functions) is not attempted until an implicit application. See Section 6.26.2 of the language specification for details and this problem for details.

One way would be to write something like this:

 provideCtx((ctx: ExecutionContext) => (a: Int) => foo(a)(ctx)) 

I'm not sure that a more general solution is possible (at least without any reflection, etc.), since we cannot even refer to foo (except for calling the method, of course) without an implicit scope.

+2
source share

All Articles