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

时间:2015-03-05 21:52:35

标签: scala akka

我想在其构造函数中将回调传递给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的实际构造需要通过显示的工厂方法,但我无法弄清楚如何通过工厂方法传递回调。

1 个答案:

答案 0 :(得分:2)

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

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

this post底部所述:

  

因为我们已经将神奇的下划线引入了   在发现功能中的一些快捷方式时,千万不要的交易   定义,如果我们想要启动eta扩展,他将再次加入   更明确地说。所以迫使编译器强制的第二个选项   进入函数的第二种方法是明确引用   方法所谓的方法值,只需引用一些下划线   [after]方法名称(而不是方法参数)