Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Akka & Case Statements

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:

  1. Is this a case of Scala's pattern matching? If so, why is there no corresponding match keyword?

  2. 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)?

like image 487
Alex Avatar asked Mar 18 '23 20:03

Alex


2 Answers

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

like image 117
Kamiel Wanrooij Avatar answered Apr 08 '23 20:04

Kamiel Wanrooij


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.

like image 28
Jonny Coombes Avatar answered Apr 08 '23 21:04

Jonny Coombes