case class与case object实战

来源:互联网 发布:韩国女主播软件 编辑:程序博客网 时间:2024/05/22 17:33

参考文献
scala 深入浅出实战经典 . 王家林

场景
case class与case object的基本使用与嵌套case

实验

package com.scode.scala/** * author: Ivy Peng * function: case class 与 case object学习 * date:2016/03/20 12.14 * sum: * 1、作用:语言级别的优化,方便传递消息与模式匹配 * 2、语法:case class className(property:proType,..)其中property默认是 val的 * 3、case object : 需要一个共享的全球唯一的对象时用 * 4、case 嵌套学习 */abstract class Personcase class Student(age:Int) extends Personcase class Worker(age:Int,salary:Double) extends Personcase object Shared extends Personabstract class Itemcase class Book(des:String,price:Double) extends Itemcase class Bundle(des:String,price:Double,items:Item*) extends Itemobject CaseLearn{  def main(args:Array[String]):Unit =  {    def caseOps(person:Person) = person match    {      //这里会从person中汲取出 age并复制给 Student.age      case Student(age)=> println("I'm "+age +" year old!")      case Worker(_,salary)=> println("I'm a worker with salary of "+salary)      case Shared => println("No property")    }    caseOps(Student(19))    caseOps(Shared)    val worker = Worker(10,1000.2)    val worker2 = worker.copy(salary=10)    def recursiveCase(item:Item) = item match    {      case Bundle(_,_,art@Book(_,_),rest@ _*)=> println("给当前实例Book一个引用名字 art :"+art.des)      case Bundle(_,_,Book(desc,_),_*) => println("Book with des:"+desc)      case _ => println("Oops")    }    recursiveCase(        Bundle(            "Spark 1.0",30.0,            Book("Scala,yes",18.0),            Bundle("",28.0,Book("java",10),Book("c++",20))              )                 )  }}
0 0