Background
I want to send a close to a remote actor. the remote actor must start closing its data and send the result. It may not be practical, but for the sake of curiosity, what I want to do now
But I notice that if the closure is created as an anonymous function, it also captures the external object and tries to marshal it, which fails if the external object is not serialized, as in this case.
class Client(server: ActorRef) extends Actor { var every = 2 override def preStart() = { println("client started. sending message....") server ! new Message((x) => x % every == 0) } }
the above code throws an exception when calling a remote member. I could define a local variable in the preStart() method
val every_ = every
and use it instead of an actor member variable. But I believe that this is not a solution. and I have to be very careful if closing is a little tricky.
An alternative is to define a class that inherits from Function1[A,B] and send its instances as a closure.
class MyFunc(every : Int) extends Function1[Int,Boolean] with Serializable { def apply(v1 :Int) : Boolean = { v1 % every == 0 } } server ! new Message(new MyFunc(every))
But this separates the definition of closure from the place in which it is used, and defeats the whole purpose of using a functional language. and also makes it difficult to determine closure logic.
Specific request
Is there a way to defer the definition of the Function1.apply body and assign the apply body when I create an instance of MyFunc from a locally defined closure?
eg.
server ! new Message(new MyFunc(every){ // not valid scala code x % every == 0 })
where every is a local variable?
Basically, I want to combine the two approaches, that is, send a Function1 object to a remote actor with the body Function1 defined by the anon function defined at the place where the Function1 instance was created.
Thanks,