scala> //PS:110, 119 scala> //psn > a40 > a60 scala> case class Marks(firstTerm:Int, secondTerm:Int) defined class Marks scala> case class Subject(name:String, marks:Marks) defined class Subject scala> val phy = Subject("physics", Marks(70, 80)) phy: Subject = Subject(physics,Marks(70,80)) scala> val eng = Subject("english", Marks(75, 85)) eng: Subject = Subject(english,Marks(75,85)) scala> val math = Subject("math", Marks(80, 90)) math: Subject = Subject(math,Marks(80,90)) scala> for { seq <- Seq(phy, eng, math) } { | val result = seq match { | // Note 1 : unapply() method is used for Extraction | // (whereas apply() is used for creating an Object) | // Note 2 : unapply()(apart from apply()) is also another | // method that has been created by the Compiler | // as part of Companion Object | case Subject("physics", Marks(70, _)) => s"Physics : $seq" | case s @ Subject("english", m @ Marks(_, _)) => | s"English mark : ${m}" | case Subject(_, _) => s"Others : $seq" | } | println(result) | } Physics : Subject(physics,Marks(70,80)) English mark : Marks(75,85) Others : Subject(math,Marks(80,90))
Example : Pattern Matching(Extraction) on Case Classes
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment