Ask is an actor request-response pattern. Instead of sending a fire-and-forget message, an actor sends a request, waits only up to a configured timeout, and maps either a response or a failure into a message for itself. The resulting message is then handled through the actor’s normal protocol. section 3.2.4 section 3.4
A request message declares a replyTo ActorRef for its response type. context.ask supplies that reply address when it creates the request, so a manager can pass Worker.Parse rather than manually constructing Parse with a reply target. The response mapper turns Success or Failure into a local command such as Report. section 3.2.3 section 3.2.7
Parsing work with a deadline
A manager creates one worker per text and asks each worker to parse it. On Success(Worker.Done), it sends itself a report naming the parsed text and worker. On Failure, it sends itself a failure report. A Timeout, such as three seconds, bounds how long each request may wait. section 3.2.4
Use ask where a bounded answer affects the next decision:
- Ask a market whether quoted odds remain available; treat a late response as failed because it may no longer reflect the market. section 12.1.3
- Keep a wallet reservation as tell plus a message adapter when it participates in a larger validation flow; chaining nested asks makes total timeout selection difficult. section 12.1.3
- Use context.ask inside an actor so the callback returns to that actor’s context; use entityRef.ask outside actor context, where no actor state is exposed. section 12.2.1
The callback is not merely response handling: it preserves actor isolation by converting an asynchronous outcome into a command. For payload-bearing requests, ask receives a function from the generated reply ActorRef to the request type. Scala case-class apply syntax lets a constructor such as Worker.Parse serve as that function. section 3.2.7 section 12.2.1
object Manager {
...
val worker: ActorRef[Worker.Command] = #1
context.spawn(Worker(file), s"worker-$text") #1
context.ask(worker, Worker.Parse) { #2
case Success(Worker.Done) => #3
Report(s"$text parsed by ${worker.path.name}") #3
case Failure(ex) => #3
Report(s"parsing '$text has failed with [${ex.getMessage()}")
...
}
Inspect the manager flow: spawn a worker, ask it with a timeout, and map Success or Failure into Report messages. section 3.2.4
