Tuesday, October 4, 2016

Sealed Class & Pattern Matching : Creating an exhaustive match...

scala> ////////////////////////////////////////////////////////////////

scala> //  Sealed Class & Pattern Matching #323

scala> //      Helps to make sure that we have covered all the

scala> //      possible Patterns in our code. If not convered,

scala> //      the compiler provides a warning

scala> //  A Sealed Class can only have Subclass in the same

scala> //      file

scala> ////////////////////////////////////////////////////////////////

scala> sealed abstract class Subject
defined class Subject

scala> case class Math(mark: Int) extends Subject
defined class Math

scala> case class History(mark:Int) extends Subject
defined class History

scala> case class Science(mark:Int) extends Subject
defined class Science

scala> case class Geography(mark:Int) extends Subject
defined class Geography

scala> case class TwoSubject(s1: Subject, s2: Subject) extends Subject
defined class TwoSubject

scala>

scala> // Whern a Sealed class is used for Pattern matching

scala> //      ... and if all the Patterns are not covered

scala> //      we get a compiler warning

scala> def checkSealed(sub: Subject) = sub match {
     |     case a: Math => println("This is math")
     | }
:26: warning: match may not be exhaustive.
It would fail on the following inputs: Geography(_), History(_), Math(_), Science(_), TwoSubject(_, _)
       def checkSealed(sub: Subject) = sub match {
                                       ^
checkSealed: (sub: Subject)Unit

scala>

scala> // Compiler warning can be also taken away using

scala> //      the annotation @unchecked

scala> def checkSealed(sub: Subject) = (sub: @unchecked) match {
     |     case a: Math => println("This is math")
     | }
checkSealed: (sub: Subject)Unit