Search code examples
scalaakkaactortraitspartialfunction

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?


Solution

  • 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 ... =>  ...
        }
    
    }