Akka/Java getContext().become with parameter?

2019-07-06 16:30发布

问题:

In Akka/Scala one is able to pass parameters to the custom receive function, so it is possible to pass the whole actor state through params, without using mutable variables.

context.become(myCustomReceive(param1, param2))

But in Java Api you can pass only Procedure which gets the received message as the only param

getContext().become( new Procedure<Object> {
  public void apply(Object param) throws Exception
  {
    // ... 
  }
}

Is there a clean way to do the same trick in Java?

回答1:

I would do it like this

class ProcedureWithParams<T> extends Procedure<T> {
   Object param1;
   Object param2;

   ProcedureWithParams(Object param1, Object param2) {
      this.param1 = param1;
      this.param2 = param2;
   }

   public void apply(Object param) throws Exception {
    //access para1 and param2 here
   }

}

getContext().become( new ProcedureWithParams(param1, param2))


标签: java scala akka