overriden bang (!) operator. Find sender - scala

When I override the bang (!) operator in Scala, it's invoked on the actor which is the recipient of the message. Is there a way I can find out who sent this msg to this actor inside the overridden bang operator?
Thanks,

Please see here how to override the behavior of the bang operator. In your particular case you can override it by wrapping the original message in an envelop containing the sender.
How to override bang operator(!) for different type of inputs in scala
How to overload bang(!) operator in Scala Actor model?
Also, please note that the Scala 2.9's actors API will become deprecated. Consider using Akka instead which does provide the functionality you are looking for.

Related

Is there a simple way to filter & narrow collections on instance type in assertj?

Can this be written as a single line?
assertThat(actualDeltas)
.filteredOn(delta -> delta instanceof Replacement)
.asInstanceOf(InstanceOfAssertFactories.list(Replacement.class))
I expected asInstanceOf to do the filtering. Alternatively, I searched for extractors or other concepts, but couldn't find any simple solution.
Is that possible with assertj?
By design, the purpose of asInstanceOf is only to provide type-narrowed assertions for cases where the type of the object under assertion is not visible at compile time.
When you provide InstanceOfAssertFactories.list(Replacement.class) as a parameter for asInstanceOf, you are telling AssertJ that you expect the object under assertion to be a List with elements of type Replacement.
While asInstanceOf will make sure that the object under test is a List, it will neither filter nor enforce that all the list elements are of type Replacement. The Replacement will ensure type-safety with subsequent methods that can be chained, for example with extracting(Function).
Currently, filteredOn(Predicate) or any other filteredOn variant is the right way to take out elements that should not be part of the assertion. If the filtering would happen outside (e.g., via Stream API), no asInstanceOf call would be needed as assertThat() could detect the proper element type based on the input declaration.

Scala : Syntactic Sugar

I have been scratching my head to understand how to read this function:
private def greeterBehavior(currentGreeting: String): Behavior[Command] =
Actor.immutable[Command] { (ctx, msg) =>
msg match {
case WhoToGreet(who) =>
greeterBehavior(s"hello, $who")
case Greet =>
println(currentGreeting)
Actor.same
}
}
Questions:
1 ) function takes string and returns Behavior[Command] . ( understood)
But .. what is Actor.immutable[Command] ?
Is this a type casting ? or is it an object ?
2) if I have to understand such syntax what is the best place or book I can refer?
To address the comments regarding the location of the API documentation for Actor.immutable:
As the Akka documentation clearly states, the Akka Typed API is still in flux:
This module is currently marked as may change in the sense of being the subject of active research. This means that API or semantics can change without warning or deprecation period and it is not recommended to use this module in production just yet—you have been warned.
Apparently you're using a pre-2.5.10 version of Akka: the Actor object was removed from the Akka Typed module in version 2.5.10.
From Akka 2.5.2 to Akka 2.5.8, there was an akka.typed.scaladsl.Actor.immutable method.
In Akka 2.5.9, the Actor.immutable method moved to the akka.actor.typed package.
In Akka 2.5.10, the akka.actor.typed.Actor object was removed. This object is still absent in 2.5.11 and 2.5.12 (the current version of Akka at the time of this writing).
Here is the Scaladoc for the last version of Actor.immutable from Akka 2.5.9:
def immutable[T](onMessage: (ActorContext[T], T) => Behavior[T]): Immutable[T]
Construct an actor behavior that can react to both incoming messages and lifecycle signals. After spawning this actor from another actor (or as the guardian of an akka.actor.typed.ActorSystem) it will be executed within an ActorContext that allows access to the system, spawning and watching other actors, etc.
This constructor is called immutable because the behavior instance does not need and in fact should not use (close over) mutable variables, but instead return a potentially different behavior encapsulating any state changes.
immutable is a method on Actor, which takes in a generic type parameter, in this case that type is Command.
Any intro to Scala material worth reading should cover generics. "Programming in Scala" and "Scala for the Impatient" are both popular.

Generic Akka ActorSystem

Is there any way to create ActorSystem[T] which will create only actors <:T ? For all other types it could throw exception or something like this.
Typed Actors: http://doc.akka.io/docs/akka/snapshot/scala/typed-actors.html.
Citing documentation: "The advantage of Typed Actors vs. Actors is that with TypedActors you have a static contract, and don't need to define your own messages, the downside is that it places some limitations on what you can do and what you can't, i.e. you cannot use become/unbecome."

what does a ! b mean in Scala?

I am reading through some Scala code and part of the program reads as follows:
clusterManager ! ClusterManagerMessages.Shutdown
clusterNotificationManager ! ClusterNotificationMessages.Shutdown
I see that ! is a unary operator so what does this code mean?
In scala language nothing (in your context), but it is usually means fire-n-forget message in scala actors. There is also ? counterpart which is used when you want to have handle to the response in a form of Future.
The ! operator is shorthand for the tell method in Scala Actor APIs. The Scaladoc for akka.actor.ActorRef provides two examples, one for each of Scala and Java. Notice how Java uses the tell method and Scala uses the ! operator.
On a personal note, I found it particularly frustrating when I was first researching Scala actors and found no explicit definition of the binary ! operator in the Scaladocs. The best resource that I have found so far for being introduced to Scala Actors is Programming in Scala (Ch. 32) by Odersky et al. If you have the time and/or dedication to gain an in-depth understanding of the Akka Actor model and what's going on beneath the hood, I recommend Akka in Action.
! is not, in this case, a unary operator. If you see code like this in Scala:
a b c
then that's most likely the b method being called on the a object passing c as parameter. And it doesn't really matter whether a, b and c are words or symbols -- Scala accepts both.
In this particular case, ! means "send message", so clusterManagement ! ClusterManagementMessages.Shutdown means send the message ClusterManagementMessages.Shutdown to the actor clusterManagement. For more information on what that means, look up information about the actor model.
So much complexity in the answers so far!
In this context, it's most certainly the (unsynchronized) message-send operator, not the unary negator operater, and it's used in the semi-standard Akka library. If you're not familiar with them, read up on Scala "Actors" and how systems can be built with loads and loads of small "actors" that communicate with each other via message sending. In this case, the code is appears to be telling a "clusterManager" to shut down, and then sending a "clusterNotificationManager" the message that it's told the clusterManager to shutdown.

akka sending a closure to remote actor

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,
Sure, you could send behaviour to actor, but it considered to be a bad practice, and your questions is a good answer on question: "why".
As BGR pointed out there is special section in documentation on this question, but it has no example.
So, when you sending a closure as message you sending some extra "implicit" state with it. It could be not mutable as said in documentation, but even in this case it can create problems.
The problem with scala here is that it not strictly functional language - it is multiparadigm language. In other words you could have code in functional paradigm side by side with code in imperative style. There is no such problems in, for example haskell, which is purely functional.
In case of your "specific query" I'll suggest you to use set of predefined functions. This is full equivalent of variant with closures but with a bit chatty syntax. Since you do not generate code during runtime all functions you use are defined in limited set and (looks like) parameterized by value. This makes your code not so flexible like with closures, but in the end it will be equivalent cases.
So, as a leitmotif of all my post: if you going to send behaviour to actor it should be rock solid atomic (in meaning have no any dependencies)