Reputation: 267010
I have an actor that I need to make abstract because it is being used as a common pattern used in many places.
abstract class SomeActor(.....) extends Actor with ActorLogging {
def receive = {
case Message1 =>
case Message2 =>
case Message3 =>
}
}
Now say I need to customize one actor implementation handles the logic for Message2, what options do I have in order to accomplish this?
Upvotes: 1
Views: 368
Reputation: 2480
The receive
function is a PartialFunction[Any, Unit]
so we can use this in our advantage. Partial functions provide some useful operators that you can use, for example PartialFunction#orElse
.
This means you can define in the parent actor a PartialFunction[Any, Unit]
then in the child actor another one and define receive by combining these too. Let's see some code!
abstract class Parent extends Actor {
def commonReceive: Receive = {
case CommonHandledMessage =>
println("common handling")
case Message =>
println("parent handling")
}
}
class Child extends Actor {
override val receive: Receive = specializedReceive orElse commonReceive
def specializedReceive: Receive = {
case Message =>
println("child handling")
}
}
However you should be careful with the way you combine these partial functions, as you might be suprised of the result. When you use the orElse combiner, partial functions basically stack up on top of each other. So you can imagine that the receive
method we defined above transforms into something like:
override val receive: Receive = {
case Message =>
println("child handling")
case CommonHandledMessage =>
println("common handling")
case Message =>
println("parent handling")
}
This means that the parent handling is basically useless here as you can deduct from the pattern match.
I guess the point here is always think how these partial functions get combined, because some pattern match branches might never be reached. In this case, the parent handling would never be reached because it is basically overriden. Other than that, partial functions are really cool!
I hope that helps :)
Upvotes: 8