One good thing about sealed traits is that standard Scala library uses these constructs a lot, and you've also seen them many times so far. It's time to learn about them. We'll start with an example:
sealed trait Season case object Autumn extends Season case object Winter extends Season case object Spring extends Season case object Summer extends Season case object Monsoon extends Season object SealedApp extends App { def season(season: Season) = season match { case Autumn => println(s"It's Autumn :)") case Winter => println(s"It's Winter, Xmas time!") case Spring => println(s"It's Spring!!") case Summer => println(s"It's summer, who likes summer anyway!") case Monsoon => println(s"It's Monsoon!!") } season(Spring) }
The result is as follows:
It's Spring!!"
Here, we defined a sealed trait named Season
. Then there're a few child season case objects extending from the sealed trait Season
. By the way, case objects are like...