I'm learning Akka for Scala, and have also been reading up on Scala's pattern matching/case statements.
In Akka, I can write an actor as follows:
class MyActor extends Actor {
def receive: Receive = {
case msg: MyMsgClass => sender ! "message received!"
}
}
Questions:
Is this a case of Scala's pattern matching? If so, why is there no corresponding match
keyword?
In the case
line, is msg
an identifier and is it required? What happens if I omit it and just use the class name (and presumably if I provide no identifier, I can't use the variable itself)?
It is a case of pattern matching, in combination with a Partial Function. In short, the partial function
{
case msg: MyMsgClass
}
only matches if there is an argument of type MyMsgClass
. It handles a 'partial subset' of possible values. This syntax generates a PartialFunction
object that handles the case where the input is a MyMsgClass
.
You can also write:
{
case MyMsgClass(value) => sender ! value
}
but in this case you only get the value
. You can even do complex things like:
{
case m @ MyMsgClass(AnotherClass(_), "this must be this string", a) => sender ! doSomething(m, a)
}
and it will nicely match only MyMsgClass
objects that have a first parameter of type AnotherClass
(regardless of its parameters, hence the _
), the exact string "this must be this string"
, and a value a
. The m @
syntax denotes that the object itself is also used, not just as a type.
Some more info: http://blog.bruchez.name/2011/10/scala-partial-functions-without-phd.html
You can see from the Scaladocs for Actor that Receive is defined as having type: type Receive = PartialFunction[Any, Unit], which effectively means that it's an abstract member defined as being a partial function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With