【问题标题】:How to wrap `this` class in ActorRef in akka actorsystem如何在akka actorsystem的ActorRef中包装`this`类
【发布时间】:2021-07-22 02:00:14
【问题描述】:

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

还有一个在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 类的 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] 做一些事情,但我查看了文档,但找不到所需的命令。我错过了什么?

【问题讨论】:

    标签: scala akka akka-actor


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-10
      • 2013-11-21
      • 1970-01-01
      • 2014-02-21
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      相关资源
      最近更新 更多