Search code examples
scalaakkaactor

Can we define trait inside a object in scala


I just started to learn scala and currently learning about Akka through this Learning Akka course

I'm confused about the code style, the author has created a trait inside a object.

 object MusicController {
  sealed trait ControllerMsg
  case object Play extends ControllerMsg
  case object Stop extends ControllerMsg

  def props = Props[MusicController]

}

I understand that Scala object provides singleton ability and a way to define all static method in class through companion object. Can anyone help me understanding this syntax ? Thanks


Solution

  • You will often see this with Actors. It is good practice to define the messages that an Actor responds to in its companion object, which happens here.

    The sealed trait part isn't really necessary. You just often see this in Scala with case classes/objects. Also, being sealed means that you will get a warning if your match is not exhaustive when you pattern match on instances of it.