Note that there are some explanatory texts on larger screens.

plurals
  1. POakka sending a closure to remote actor
    primarykey
    data
    text
    <p><strong>Background</strong></p> <p>i want to send a closure to a remote actor. remote actor should run the closure on its data and send back the result. <em>May be it is not advisable, but for curiosity's sake that's i want to do now</em></p> <p>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.</p> <pre><code>class Client(server: ActorRef) extends Actor { var every = 2 override def preStart() = { println("client started. sending message....") server ! new Message((x) =&gt; x % every == 0) } } </code></pre> <p>the above code generates exception while calling the remote actor. i could define a local variable in the method <code>preStart()</code></p> <p><code>val every_ = every</code> </p> <p>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.</p> <p>Alternative is to define a class inheriting from <code>Function1[A,B]</code> and send its instances as closure.</p> <pre><code>class MyFunc(every : Int) extends Function1[Int,Boolean] with Serializable { def apply(v1 :Int) : Boolean = { v1 % every == 0 } } server ! new Message(new MyFunc(every)) </code></pre> <p>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.</p> <p><strong>Specific Query</strong></p> <p>Is there a way i can defer defining the body of the <code>Function1.apply</code> and assign the body of <code>apply</code> when i create the instance of <code>MyFunc</code> from a locally defined closure?</p> <p>e.g. </p> <pre><code>server ! new Message(new MyFunc(every){ // not valid scala code x % every == 0 }) </code></pre> <p>where <code>every</code> is a local variable?</p> <p>basically i want to combine the two approaches i.e. send an object of <code>Function1</code> over to remote actor with the body of <code>Function1</code> defined by an anon function defined in place where <code>Function1</code> instance is created.</p> <p>Thanks,</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload