scala> ////////////////////////////////////////////////////////////////
scala> // Pattern matching on 'case class' : Example... #309
scala> ////////////////////////////////////////////////////////////////
scala> 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> //By Creating a variable that is starting with a Capital Letter
scala> //we are creating a Symbolic Constant #313
scala> val Mark = 50
Mark: Int = 50
scala> val newmark = 55
newmark: Int = 55
scala>
scala> def checkSubject(sub: Subject) = sub match {
| //Math(10) : Represets a Constructor Pattern #310
| //10 : Represents the Constant Pattern
| case Math(10) => println("Math : mark -> 10")
|
| //x : Represents variable pattern
| case Math(x) => println("Math : x -> " + x)
|
| // _ : Represents Wild card pattern
| case History(_) => println("history. Not possible to access mark")
|
| // Variable binding using @ ; 320
| case TwoSubject(Science(x), geo @ Geography(50)) => {
| println("Twosubject : Science -> " + x + ", Geo -> " + geo)
| }
|
| //Although this looks like a Variable pattern(as we are using
| // variable name), this is actually a Constant Pattern
| // as the Variable name starts with a Capital Letter(so it
| // is a Symbolic Constant)
| case Science(Mark) => println("Science : Mark : 50")
|
| //Variable names starting with lower case letter can
| // also be made symbolic constants by using backtics #315
| case Science(`newmark`) => println("Science : Mark -> 55")
|
| // Without this wildcard ( ie ... _), we will get
| // match error
| case _ => println("Nothing matched...")
| }
checkSubject: (sub: Subject)Unit
scala>
scala> checkSubject(Math(10))
Math : mark -> 10
scala> checkSubject(Math(50))
Math : x -> 50
scala> checkSubject(History(60))
history. Not possible to access mark
scala> checkSubject(TwoSubject(Science(10), Geography(50)))
Twosubject : Science -> 10, Geo -> Geography(50)
scala> checkSubject(TwoSubject(Science(10), Geography(60)))
Nothing matched...
scala> checkSubject(Science(50))
Science : Mark : 50
scala> checkSubject(Science(55))
Science : Mark -> 55
scala> checkSubject(Geography(90))
Nothing matched...