使用 Context.actorOf 时如何将回调函数传递给 akka actor 构造函数?

How do I pass a callback function to an akka actor constructor when using Context.actorOf?

我想在其构造函数中将回调传递给 akka actor:

object FSMActorWithCallback {
  type Tracer = (Int, NodeState, NodeData, ActorRef, Any) => Unit
}

class FSMActorWithCallback(tracerCallback: FSMActorWithCallback.Tracer) extends FSMAwesomeActor
  // method is called each FSM Event so we can record current state and next message 
  override def trace(state: NodeState, data: NodeData, sender: ActorRef, msg: Any) : Unit = {
    // different tracing callback for different test rigs such as unit tests or integration tests
    tracerCallback(nodeUniqueId, state, data, sender, msg)
  }
}

这可以让我使用 new 定义原始 actor,但我需要使用 actorOf 工厂方法让 actor 正确连接到系统中:

class Supervisor extends Actor {

  def outputStateTrace(state: NodeState, data: NodeData, sender: ActorRef, msg: Any): Unit = { 
    /*actually make a binary log for analysis of complex failures*/
  }

  // COMPILE ERROR "follow this method with _ if you wan to treat it as a partially applied function" 
  var child = contact.actorOf(Props(classOf[FSMActorWithCallback], outputStateTracer) 

  // seems to work fine but not what i need
  val childRaw = new FSMActorWithCallback(tracer) 

}

actor 的实际构造需要通过所示的工厂方法,但我不知道如何通过工厂方法传递回调。

您传递的是方法而不是函数。编译器告诉您使用 Eta 扩展将其转换为函数。

var child = contact.actorOf(Props(classOf[FSMActorWithCallback], outputStateTracer _)

this post底部所述:

Since we’ve already introduced the magical underscore as a jack-of-all-trades while discovering some shortcuts within function definition, he’s again on board if we want to initiate eta expansion more explicitly. So the second option to force the compiler to coerce the second method into a function is to explicitly refering to the methods so called method value, simply by quoting some underscore [after] the method name (instead of the methods arguments)