Reader small image

You're reading from  Learning Scala Programming

Product typeBook
Published inJan 2018
Reading LevelBeginner
PublisherPackt
ISBN-139781788392822
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Vikash Sharma
Vikash Sharma
author image
Vikash Sharma

Vikash Sharma is a software developer and open source technology evangelist. He tries to keep things simple, which helps him write clean and manageable code. He has invested a large amount of time learning and implementing Scala code, and he has authored video courses for Scala. He works as a developer at SAP Labs.
Read more about Vikash Sharma

Right arrow

Sealed traits


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...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Learning Scala Programming
Published in: Jan 2018Publisher: PacktISBN-13: 9781788392822

Author (1)

author image
Vikash Sharma

Vikash Sharma is a software developer and open source technology evangelist. He tries to keep things simple, which helps him write clean and manageable code. He has invested a large amount of time learning and implementing Scala code, and he has authored video courses for Scala. He works as a developer at SAP Labs.
Read more about Vikash Sharma