如何在 akka actorsystem 的 ActorRef 中包装 `this` class

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

我正在尝试在 Akka 中创建两个简单的 actor,一个创建一个世界(城市案例列表 classes)和 return 返回给 init actor 的消息。我的 bootstrap class 在 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
      }
  }
}

还有 class 在 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
  }
}

然后我会在 ActorInit class 的 onMessage 方法中添加另一个案例,以侦听来自 World 演员的 WroldMap 消息。但是,当我 运行 这样做时,出现以下错误:

[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]                                        ^

我知道我需要对签名 T => akka.actor.typed.ActorRef[T] 做一些事情,但我查看了文档,但找不到所需的命令。我错过了什么?

我在查看更多文档后找到了答案。我应该一直在使用 context.self。所以我的 Init 案例看起来像:

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

我需要稍微更改 Create 案例 class:

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