30.模式匹配高级实战:嵌套的Case class

来源:互联网 发布:完美循证医学数据 编辑:程序博客网 时间:2024/06/05 06:31

有时候要表达一种类似于集合类型的元素,而元素本身的表示又是case class的实例,这时候就要用到嵌套

eg:书店中有很多书,很多书可以构成集合,而书本身用case class表达,集合也用case class表达。这时候就用嵌套。


package ce.scala.pp//7abstract class Itemcase class Book(description : String, price : Double) extends Itemcase 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讲 由王家林老师讲解


阅读全文
0 0
原创粉丝点击