I would like to propagate a request context implicitly in a system of collaborating actors.
To simplify and present the situation, my system has multiple actors and the messages passed to these actors need to include this RequestContext object.
ActorA receives messages of type MessageA ActorB receives messages of type MessageB
when ActorA needs to send a message to ActorB, as part of the handling of MessageA, it performs business logic, and then constructs a MessageB from results of the logic as well as the RequestContext available in MessageA and then sends it to ActorB
def handle(ma:MessageA) {
val intermediateResult = businessLogic(ma)
actorB ! MessageB(intermediateResult, ma.requestContext)
}
We have a slew of messages to be handled, and explicitly passing around the requestContext is cumbersome.
I am trying of creative ways to use Scala's implicits feature to avoid explicitly injecting the RequestContext embedded within incoming message into the outgoing message.
The messages are case classes (and they need to be). I have read about implicits rules but bringing an attribute of an object into current implicit scope appears far-fetched.
This, I am sure should be a common requirement. Any suggestions ?
Thanks.
In my opinion, the easiest way is to make your val implicit in the case class.
case class MessageA(req: RequestA)(implicit val ctx: RequestContext)
case class MessageB(req: RequestB)(implicit val ctx: RequestContext)
def businessLogic(req:RequestA):RequestB
def handle(ma: MessageA): Unit = {
// import all the members of ma so that there is a legal implicit RequestContext in scope
import ma._
val intermediateResult = businessLogic(req)
actorB ! MessageB(intermediateResult)
}