简体   繁体   中英

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

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.

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