How to implement get () in Akka Actor

I am in the process of converting Akka UntypedActors to Java code in their Scala equivalent.

However, it’s difficult for me to understand how to correctly implement the receive () abstract method. ScalaDoc is a bit confusing, and most of the examples I see just include String messages!

My actor can support several types of messages, and this is my solution:

override def receive = {
    case message if message.isInstanceOf[ClassOne] => {
        // do something after message.asInstanceOf[ClassOne]
      }
    case message if message.isInstanceOf[ClassTwo] => {
      // do something after message.asInstanceOf[ClassTwo]
    }        
    case message => unhandled(message)
  }

Is there a better way to achieve the above?

+3
source share
3 answers

receive type PartialFunction[Any,Unit], , , Scala - , . , :

def receive = {
    case classOneMessage : ClassOne => {
        // do something
      }
    case classTwoMessage : ClassTwo => {
      // do something 
    }        
    case _ => someCustomLogicHereOtherWiseThereWillBeASilentFailure 
              //you can, but you don't really need to define this case - in Akka 
              //the standard way to go if you want to process unknown messages
              //within *this* actor, is to override the Actor#unhandled(Any) 
              //method instead
  }

tutorial , case - Akka, , Akka case ActorIdentity.

+6
override def receive = {
  case c: ClassOne =>
      // do something after message.asInstanceOf[ClassOne]
  case c: ClassTwo =>
  // do something after message.asInstanceOf[ClassTwo]
  case message => unhandled(message)
}

case, .

case class ClassOne(x: Int, y: String)
case class ClassTwo(a: Int, b: Option[ClassOne])

override def receive = {
  case ClassOne(x, y) =>
      println(s"Received $x and $y")
  case ClassTwo(a, Some(ClassOne(x, y)) if a == 42 =>
      // do something
  case ClassTwo(a, None) =>
  case c @ ClassOne(_, "foo") => // only match if y == "foo", now c is your instance of ClassOne
}    

.

+9

receiveis a regular partial function in Scala. You can write something like this in your case:

  case class Example(number: Int, text: String)

  override def receive = {
    case message: ClassOne =>
      // do something with ClassOne instance
    case message: ClassTwo =>
      // do something with ClassTwo instance
    case Example(n, t) =>
      println(t * n)
    case Example(n, t) if n > 10 =>
      println("special case")
  }

You do not need to include a special case for unprocessed messages if your application logic does not require processing of all possible messages.

The first two cases, matching the message type and subtypes, will also match. The latter not only corresponds to the type Example, but also “deconstructs” it by means of comparison with the sample.

+1
source

All Articles