Search code examples
scalaakkaactorfsm

Akka: FSM - reuse actor with different subtype of message


Let's say I have following messages:

trait Msg { def c: Int }
case class MsgType1(c: Int) extends Msg
case class MsgType2(c: Int) extends Msg

Now, I want to reuse the same FSM actor for different type of Msg as below. In this case we use generic type Msg as a message type. When I am instantiating this actor I want somehow to indicate which type of Msg I want to receive.

class ActorFSM1() extends FSM[s, Data] {
  when(SomeState) {
    case Event(msg: Msg, data: Data) =>

Instead of duplicating the code as below:

class ActorFSM1() extends FSM[s, Data] {
  when(SomeState) {
    case Event(MsgType1(c), data: Data) =>

class ActorFSM2() extends FSM[s, Data] {
  when(SomeState) {
    case Event(MsgType2(c), data: Data) =>

Is this possible? Note: I do not want to have different case statement within same actor. They should be different actors which happen to receive different subtype of Msg. Rest of the logic is identical among different instances.


Solution

  • class ActorFSM1[T<:Msg] extends FSM[s, Data] {
        when(SomeState) {
            case Event(msg: T, data: Data) =>