Scala: Syntax of passing an execution context to Future's map function

1.8k views Asked by At

A previous version of this question did not come to the point, so I tried to boil it down:

The map function of a Future takes an ExecutionContext, as shown below (taken of API 2.10.3)

def map[S](f: (T) ⇒ S)(implicit executor: ExecutionContext): Future[S] 

I want to pass my own ExecutionContext, but I do not succeed. It seems as if I do not get the syntax right.

How can I pass my ExecutionContext to a map function of a Future?

What I have got is:

val executorService  = Executors.newFixedThreadPool(9)
val executionContext = ExecutionContext.fromExecutorService(executorService)

def myFunction(mt : MyType): Unit = println("my function")
def getSomeFuture()(executor: ExecutionContext): Future[MyType] = {..}

// function is served by my execution context. A Future is returned.
val f = getSomeFuture()(executionContext)

// compiles if I provide the standard global execution context - sth. I do NOT want
f map (myFunction)

// does not compile
f map (myFunction)(executionContext)

// does not compile
f map (item => println("sth."))(executionContext)
2

There are 2 answers

1
Robin Green On BEST ANSWER

Try

f.map(myFunction)(executionContext)

In general, I find that using spaces instead of dots behaves unintuitively, so I try to avoid that unless I am copy-pasting an example.

0
kong On

FYI if you want to use the space syntax for the method invocation, you need to wrap the whole first part of the expression in parens:

(f map myFunction)(executionContext)

Otherwise the compiler thinks you're trying to pass the executionContext to myFunction instead of the function returned by f map myFunction.