Scala学习笔记20【Scala 模式匹配之case class实战】

简单来说,Scala的case class就是在普通的类定义前加case关键字,然后你可以对这些类来模式匹配。
case class带来的最大的好处是它们支持模式匹配

简单的case class 模式匹配代码示例:

package com.yl.Scala

abstract class Person //定义抽象类Person

case class Student(age: Int) extends Person //caseStudent
case class Worker(age: Int, salary: Double) extends Person
case object Shared extends Person //case 单例对象

object CaseClass {
  def main(args: Array[String]){

    def caseTest(person: Person) = person match{
      case Student(age) => println("I am " + age + " years old.")   //与Student类对象类型进行匹配
      case Worker(_, salary) => println("I got only " + salary + " ...")//与Worker类对象类型进行匹配
      case Shared => println("单例对象Shared,直接用本身进行传递") //与单例对象Shared对象类型进行匹配
    }

    caseTest(Student(24))
    caseTest(Worker(34, 1000))
    caseTest(Shared)

    val worker1 = Worker(24, 3800)  //case class 实例化可免去new
    val worker2 = Worker(25, 4100)
    val worker3 = Worker(26, 8000)
    val worker4 = Worker(27, 9500)

    caseTest(worker1)
    caseTest(worker2)
    caseTest(worker3)
    caseTest(worker4)
  }
}

运行结果:

I am 24 years old.
I got only 1000.0 ...
单例对象Shared,直接用本身进行传递
I got only 3800.0 ...
I got only 4100.0 ...
I got only 8000.0 ...
I got only 9500.0 ...

Scala 中嵌套的case class的模式匹配示例:

package com.yl.Scala

abstract class Item
case class Book(description : String, price: Double) extends Item
case class Bundle(description : String, price: Double, items: Item*) extends Item //含有嵌套类类型Item

object CaseClassAdvanced {
  def main(args: Array[String]){
    def caseTest(thing: Item) = thing match{

      //Bundle
      case Bundle(_, _, art @Book(_, _), rest @ _*)
           => println(art.description + " price: " + art.price + "$") //嵌套Book类实例对象art
      //Book
      case maths @Book(_, _) => println(maths.description + " price: " + maths.price + "$")

      case _  => println("something else.")
    }

    caseTest(Bundle("sth.", 34.22, Book("Book name : Art", 24.45))) 
    caseTest(Book("Book name : Maths", 55.33))

  }
}

运行结果:

Book name : Art  price: 24.45$
Book name : Maths  price: 55.33$

你可能感兴趣的:(模式匹配,case-class)