30.模式匹配高級實戰:嵌套的Case class

有時候要表達一種類似於集合類型的元素,而元素本身的表示又是case class的實例,這時候就要用到嵌套

eg:書店中有很多書,很多書可以構成集合,而書本身用case class表達,集合也用case class表達。這時候就用嵌套。


package ce.scala.pp

//7
abstract class Item
case class Book(description : String, price : Double) extends Item
case class Bundle(description : String, price : Double, item : Item*) extends Item  
//Item*的意思是:可以有若干個Item類型的成員,可以是Book,也可以是Bundle,類似json的表達


object Pattern_Match_Case_Class_Nested_30 {

  def main(args: Array[String]): Unit = {
     def caseclass_nested(person : Item) = person match{
       case Bundle(_,_, Book(descr, _), _*) => println("The first description is "+ descr )
       //case Bundle(_,_,art @Book(_,_), rest @ _*) => println(art.description + " " + art.price)  //art指向了Book這個對象,rest指向了_*
       case _ => println("oops!")
     }
     
     caseclass_nested(Bundle("111 special" , 30.0, 
         Book("scala for the spark developer", 69.95),
         Bundle("hadoop", 40.0,
             Book("hive", 79.95),
             Book("hbase", 32.95))))
             
    caseclass_nested(Bundle("1212 special" , 35.0, Book("spark for the Impatient", 39.95)))             
             
  }
}

註釋掉第二行,輸出:

The first description is scala for the spark developer
The first description is spark for the Impatient

註釋掉第一行,輸出:

scala for the spark developer 69.95
spark for the Impatient 39.95


參考資料來源於大數據夢工廠 深入淺出scala 第30講 由王家林老師講解


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章