Search code examples
scalaakkaakka-typed

Send message to parent actor in Akka Typed


Title is self-explanatory, I want to be able to send a message to a parent actor (meaning I want parent's ActorRef). In Akka Classic (untyped), the ActorRef for a parent actor can be obtained from the child's ActorContext via:

context.parent

(see, for instance, this question (in Java)).

However, the akka.actor.typed.scaladsl.ActorContext in Akka Typed does not expose an ActorRef for the parent. Is there an idiomatic means in Scala to obtain an ActorRef for the parent actor?


Solution

  • If you're in typed Akka, the only [Scala] type that could encompass ActorRefs of all possible parent actors is ActorRef[Nothing], which is an ActorRef you can't send messages to, so that's of limited utility.

    At least for as long as the classic APIs exist:

    import akka.actor.typed.scaladsl.adapter._
    
    type ClassicActorRef = akka.actor.ActorRef
    
    val parentActorRef = context.toClassic.parent
    

    This will be an untyped ActorRef, i.e. you're free to send messages which the parent actor will never accept.

    If you want a typed reference to an actor's parent, you'll need to embed that when spawning the child actor, just as if you want a typed reference to the sender of the current message you need to embed replyTos in your protocol.

    (context.sender is absent in the typed ActorContext for the same reason that context.parent is absent; the workaround for replicating classic context.sender is analogous: context.toClassic.sender)