Scala-akka类型:如何从ActorRef到Actor';s实例并发送消息本身?
我想将消息从Actor实例(case类/它的行为创建的类)发送到它的Actor 我通过保存实例获得它,然后在其中保存Scala-akka类型:如何从ActorRef到Actor';s实例并发送消息本身?,scala,reference,akka,actor,self,Scala,Reference,Akka,Actor,Self,我想将消息从Actor实例(case类/它的行为创建的类)发送到它的Actor 我通过保存实例获得它,然后在其中保存ActorRef: val (instance, behaviour) = MyActorInstance(Nothing) val actor = ActorSystem(instance, "SomeName123") //save it here instance.setMyActor(actor) object MyActorInstance { def apply(
ActorRef
:
val (instance, behaviour) = MyActorInstance(Nothing)
val actor = ActorSystem(instance, "SomeName123")
//save it here
instance.setMyActor(actor)
object MyActorInstance {
def apply(ctx: ActorContext[Commands]): (MyActorInstance,Behavior[Commands]) = {
val actorInstance = new MyActorInstance(ctx)
val behaviour: Behavior[Commands] =
Behaviors.setup { context =>
{
Behaviors.receiveMessage { msg =>
actorInstance.onMessage(msg)
}
}
}
(actorInstance,behaviour)
}
}
class MyActorInstance(context: ActorContext[Commands]) extends AbstractBehavior[Commands](context) {
protected var myActorRef: ActorRef[Commands] = null
def setMyActor(actorRef: ActorRef[Commands]): Unit = {
myActorRef = actorRef
}
override def onMessage(msg: Commands): Behavior[Commands] = {
msg match {
case SendMyself(msg) =>
myActorRef ! IAmDone(msg)
Behaviors.same
case IAmDone(msg) =>
println(s"Send $msg to myself!")
Behaviors.same
}
}
}
在这里,我将ActorRef
保存到Actor中,用于var myActorRef
中的实例。
然后我使用该myActorRef
通过sendMilf
消息将消息从参与者实例发送到自身
但是,正如您所看到的,我使用的是变量,这并不好:为了保存ActorRef
,需要将myactorrestance
类的实例的字段myActorRef
从null
重写为ActorRef
——只有variables才可能
如果我尝试使用val并通过为new重写其实例来创建不可变类,然后将其从旧交换到新,那么我的ActorActor
仍然链接到旧实例,其中myActorRef==null
现在我找到了一种方法:只使用var
而不是val
或不可变类
但我想用val或者什么都不用。
为此,我需要从它的实例中获取ActorRef,但是如何获取呢?没有理由进行如此复杂的舞蹈,只需使用
ctx.self
。在询问之前,请至少阅读最基本的文档,这甚至可以节省您的时间