Tuesday, 29 March 2016

Sealed Trait

A sealed trait can only be extended within the file in which it is defined.
The compiler can use this to perform exhaustiveness checking. 
Another idiom related to sealed traits is to provide an alternative to enums.

object ScalaEnum extends App {
  sealed trait WeekDay
  case object Sun extends WeekDay
  case object Mon extends WeekDay
  case object Tue extends WeekDay
  case object Wed extends WeekDay
  case object Thu extends WeekDay
  case object Fri extends WeekDay
  case object Sat extends WeekDay

  def m(p: WeekDay) = println(p)
  m(Sat) // prints Sat
}




The case object is used when there is no instance-specific state! It is a kind of a singleton.

No comments:

Post a Comment