Showing posts with label aabat| @. Show all posts
Showing posts with label aabat| @. Show all posts

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

Sequence Pattern : Example...

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

scala> //  All Reference Classes in Scala extends AnyRef

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

scala> def patternFn(x: AnyRef): Unit = x match { //#315
     |     case List(1, _) => println("This is ; List(1, _)")
     |
     |     // Variable Binding : @ is used to bind a Variable #320
     |     case x @ List(2, _) => println("This is. -> " + x)
     |
     |     // _* represents : Can be any no of elements
     |     case List(3, _*) => println("This is .. -> " + x)
     | }
patternFn: (x: AnyRef)Unit

scala>

scala> patternFn(List(1, 2))
This is ; List(1, _)

scala> patternFn(List(2, 3))
This is. -> List(2, 3)

scala> patternFn(List(2, 3, 4, 5))
scala.MatchError: List(2, 3, 4, 5) (of class scala.collection.immutable.$colon$colon)
  at patternFn(<console>:23)
  ... 48 elided

scala> patternFn(List(3, 4, 5, 6, 7))
This is .. -> List(3, 4, 5, 6, 7)