Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a partially implemented partial function in scala

I'm using the Akka actors library here. The actors library defines a partial function "receive" which an actor that extends "actor" must implement to deal with various messages. I am creating a trait hierarchy for my application where trait "clockActor" extends Actor and "MasterClock" and "SubClock" extend "clockActor". I'm looking to add the common functionality of clocks in to the "clock" trait's receive function but then how to I add extra functionality to the receive function in the master and sub clock traits?

In short, I need a way to add extra case statements to a partial function. Ideas?

like image 799
Alex Avatar asked Jan 09 '13 14:01

Alex


2 Answers

As already suggested, you could easily compose PartialFunctions using orElse

trait ClockActor {

    def commonOp = {
        case ... => ...
    }

}

class MasterClock extends Actor with ClockActor {

    def receive = commonOp orElse masterOp

    def masterOp = {
        case ... =>  ...
    }

}

class SubClock extends Actor with ClockActor {

    def receive = commonOp orElse subOp

    def subOp = {
        case ... =>  ...
    }

}
like image 55
pagoda_5b Avatar answered Sep 28 '22 09:09

pagoda_5b


One thing that comes to mind is to do something like this:

trait ClockActor {
  def pf:PartialFunction[String, Boolean] = {
    case "a" => true
    case v if(_pf.isDefinedAt(v)) => _pf.apply(v)
  }

  def _pf:PartialFunction[String, Boolean] = Map.empty
}

object MasterClock extends ClockActor {

  override def _pf:PartialFunction[String, Boolean] = {
    case "b" => false
  }

  println(pf("a"))
  println(pf("b"))

}

which will output:

scala> MasterClock
true
false

The value true comes from the definition in the partial function of the Trait ClockActor, the falsecomes from the Object MasterClock.

like image 39
jcern Avatar answered Sep 28 '22 09:09

jcern