有时候要表达一种类似于集合类型的元素,而元素本身的表示又是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