简体   繁体   中英

How to share logic between cases in pattern matching

I have an actor where I need do something based on message hierarhy:

object MyActor {

    trait UpdateMessage
    case class UpdateOne() extends UpdateMessage
    case class UpdateTwo() extends UpdateMessage
    case class Other()

}

There is a same logic on UpdateMessage . You can see, that updateOneAndTwoLogic() calls two times:

class MyActor extends Actor {

    def receive: PartialFunction[Any, Unit] = {
        case UpdateOne() => {
          updateOneAndTwoLogic() //repeated
          updateOne()
        }
        case UpdateTwo() => {
          updateOneAndTwoLogic() //repeated
          updateTwo()
        }
        case Other() => {
          ...
        }
    }
}

In UntypedActor from java api, I can do something like:

public void onReceive(Object message) {
    if (message instanceof UpdateMessage)
        updateOneAndTwoLogic();
    if (message instanceof UpdateOne)
        updateOne();
    if (message instanceof UpdateTwo)
        UpdateTwo();
    if (message instanceof Other)
        ...
}

where updateOneAndTwoLogic() don't repeats.

How to remove duplicate calls in scala version?

You can use the | syntax while pattern matching in Scala.

case msg @ (UpdateOne() | UpdateTwo()) => 
   updateOneAndTwoLogic()
   msg match {
     case UpdateOne() => updateOne()
     case UpdateTwo() => updateTwo()
   }

Suggestion

use case objects instead of case classes with empty parenthesis.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM