https://twitter.github.io/scala_school/zh_cn/basics2.html这篇文章介绍了一个样本类的实用例子,受益匪浅。

    在使用模式匹配case match时,可能会遇到如下场景

    1. def calcType(calc: Calculator) = calc match {
    2. case _ if calc.brand == "HP" && calc.model == "20B" => "financial"
    3. case _ if calc.brand == "HP" && calc.model == "48G" => "scientific"
    4. case _ if calc.brand == "HP" && calc.model == "30B" => "business"
    5. case _ => "unknown"
    6. }

    OK,写起来有点繁琐。我们用case class来改造它。

    创建case class Calculator

    1. case class Calculator(brand: String, model: String)

    然后模式匹配就可以精简成如下代码块:

    1. def calcType(calc: Calculator) = calc match {
    2. case Calculator("HP", "20B") => "financial"
    3. case Calculator("HP", "48G") => "scientific"
    4. case Calculator("HP", "30B") => "business"
    5. case case _ => "Calculator of unknown type"
    6. }