简体   繁体   中英

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

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)

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM