Rawle Ramkeesoon
Rawle Ramkeesoon

Reputation: 101

Use case classes as messages in Scala

Am following sample code in the Horstman book (pages 291-292) to define and use case classes as messages in a simple Scala actor system.

The problem is the case classes are not being recognized in the receive pattern matching and control is falling through to the case _ => statement.

The code is listed below. Everything works with non case class messages.

SENDER: In actor Rcoord the act method is:

def act() {
  alive(9000) 
  register('rcoord, self) 
  proc_reg.start                   // start the process register actor  

  loop {
    try {
      receive {
        case 'process => 
          process_counter += 1
          process_number = process_counter
          spawn_process(process_number, sprocs)
          case class CreateTS(xxx: Int)
          proc_reg ! CreateTS(process_number)

        case 'stats => 
          Console.println("received msg from client to view statistics")
          //sender ! 'ok

        case 'stop => 
          Console.println("received msg that client is terminating")
          //sender ! 'bye
      } // end receive
    }
    catch
    {

RECEIVER: In actor proc_reg the act method is:

def act() {
  Console.println("process register started")

  case class CreateTS(process_number: Int)
  case class UpdateTS(process_number: Int)

  loop {
    receive {
      case CreateTS(process_number) =>
        Console.println("create TS msg received from process "+process_number)
        register_proc(process_number)

      case UpdateTS(process_number) =>
        Console.println("update TS msg received for process "+process_number)
        update_proc(process_number)

      case _ =>
        Console.println("sender is: "+sender.toString)
        //Console.println("full msg is: "+Msg.toString)
    }  // end receive
  }    // end loop
}      // end act()

Upvotes: 0

Views: 307

Answers (1)

senia
senia

Reputation: 38045

You have 2 different classes with the same name CreateTS.

You are sending CreateTS defined in sender and trying to receive message of other type with the same name in receiver.

You should move declarations of case classes from method body so it will be in scope of both methods.

Note that scala actors are deprecated, you should use akka actors.

Upvotes: 5

Related Questions