How to wrap `this` class in ActorRef in akka actorsystem

201 Views Asked by At

I am trying to create two simple actors in Akka, one which creates a world (list of city case classes) and return the message back to the init actor. I have my bootstrap class here in Main.scala

object ActorInit {
  sealed trait Command
  case object Init extends Command

  def apply(): Behavior[Command] = Behaviors.setup(context => new ActorInit(context))
}

class ActorInit(context: ActorContext[ActorInit.Command])
extends AbstractBehavior[ActorInit.Command](context) {
  import ActorInit._
  override def onMessage(msg: Command): Behavior[Command] = msg match {
      case Init => {
        val world = context.spawn(World(),"world")
        world ! World.Create(200,200,5,this)  // what do I wrap "this" in?
        this
      }
  }
}

And a class to create my world in World.scala

object World {
  sealed trait Command
  case class Create(width: Int, height: Int, count: Int, replyTo: ActorRef[ActorInit]) extends Command
  case class WorldMap(cities: List[City]) extends Command

  def apply(): Behavior[Command] = Behaviors.setup(new World(_))

  case class City(x: Int, y: Int)
}

class World(context: ActorContext[World.Command])
extends AbstractBehavior[World.Command](context) {
  import World._

  override def onMessage(msg: Command): Behavior[Command] = msg match {
    case Create(width, height, count, replyTo) => {
      replyTo ! WorldMap(generateCityList(width, height, count))
      this
    }
  }

  private def generateCityList(width: Int, height: Int, count: Int): List[City] = {
    // Create city list
  }
}

I then would add another case in my onMessage method in the ActorInit class to listen for a WroldMap message from the World actor. However when I run this I get the following error:

[error] /home/matt/documents/small_projects/akka_TSP/src/main/scala/Main.scala:27:4
0: type mismatch;
[error]  found   : small.tsp.ActorInit
[error]  required: akka.actor.typed.ActorRef[small.tsp.ActorInit]
[error]         world ! World.Create(200,200,5,this)
[error]                                        ^

I know I need to do something with the signature T => akka.actor.typed.ActorRef[T] but I looked through the documentation and I couldn't find the required command. What am I missing?

1

There are 1 best solutions below

0
On BEST ANSWER

I found my answer after looking through more of the documentation. I should have been using context.self. So my Init case looks like:

      case Init => {
        val world = context.spawn(World(),"world")
        world ! World.Create(200,200,5,context.self)
        this
      }

and I need to change the Create case class slightly:

  case class Create(width: Int, height: Int, count: Int, replyTo: ActorRef[ActorInit.Command]) extends Command