Inserting implicit argument


#1

I would like to define a withContext function that could be used this way:

withContext(exec) {
  Future(...)
  Future(...)
}

where exec is an execution context and all the futures in the body use it for their implicit argument. I tried using macros, but the compiler still complains about the missing execution context.

Can it be done?

MC


#2

In Dotty this is trivial: https://scastie.scala-lang.org/eADbhdCeT0OWNfnhY9VvYg

In current Scala you’ll have to write

withContext(exec) { implicit ctx =>
  Future(...)
  Future(...)
}

Using a macro instead will be hard, because the things that you pass to the macro will have to typecheck first. Which means you can’t just let the macro insert the implicit ExecutionContext afterwards. Maybe you could make it typecheck by importing Implicits.global and then make the macro switch the implicit arguments with another ExecutionContext instead. But that’s pretty ugly.