sealed keyword in Scala




sealed classes or traits can only be extended within the same file where it is defined. This is especially useful while creating the Algebraic Data Types.

Here are some of the characteristics of sealed traits

  • sealed traits should be extended within the same file so that the compiler knows all the possible subtypes otherwise the compiler can emit warnings if a match/case expression is not exhaustive
  • it cannot be extended anywhere else the same file
  • should only be used if all the subtypes are early known in advance.
  • this can be a way of creating something like an enum in Java


we can see the use of sealed traits in scala's Option like

sealed trait Option[+A]

final case class Some[+A] extends Option[A]
object None extends Option[Nothing]

so if we use these traits with pattern matching like this then we will get a compile error saying
Warning: match may not be exhaustive. It would fail on the following input: None

opt match {
    case Some(a) => "hello"
}

and another benefit of using this is we don't need to write the default case for the match in scala is using the sealed subclasses.

opt match {
    case Some(a) => "hello"
    case None => None
    case _ => "" // we dont need this here 
}

creating a enum using sealed

sealed case class Status(value: String)
  object ProgressStatus {
  object IN_PROGRESS extends Status("IN_PROGRESS")
  object ACCEPTED extends Status("ACCEPTED")
  object REJECTED extends Status("REJECTED")
  val values = Seq(IN_PROGRESS, ACCEPTED, REJECTED)
}

to get a value:
Status.IN_PROGRESS.value

to get all values:
Status.values

Comments

Popular posts from this blog

Functional Programming in Java - Part 1

Akka Actors in Java - Part 1