Background
i want to send a closure to a remote actor. remote actor should run the closure on its data and send back the result. May be it is not advisable, but for curiosity's sake that's i want to do now
But i observe that if a closure is created as an anonymous function, it captures the outer object also and tries to marshal it, which fails if the outer object is not serializable, 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 generates exception while calling the remote actor. i could define a local variable in the method preStart()
val every_ = every
and use it in place of actor member variable. But i feel it is a workaround not a solution. and i will have to be very careful if the closure is any bit more complex.
Alternative is to define a class inheriting from Function1[A,B]
and send its instances as 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 closure definition from the place it is used, and defeats the whole purpose of using a functional language. and also makes defining the closure logic more difficult.
Specific Query
Is there a way i can defer defining the body of the Function1.apply
and assign the body of apply
when i create the instance of MyFunc
from a locally defined closure?
e.g.
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 i.e. send an object of Function1
over to remote actor with the body of Function1
defined by an anon function defined in place where Function1
instance is created.
Thanks,
Funtion1[A,B] 's apply()
method dynamically? like how we define anonymous class methods in Java when instantiating an interface – weimaFunction1
at the time of creation. Thx :) – weima