https://twitter.github.io/scala_school/zh_cn/basics2.html这篇文章介绍了一个样本类的实用例子,受益匪浅。
在使用模式匹配case match时,可能会遇到如下场景
def calcType(calc: Calculator) = calc match {
case _ if calc.brand == "HP" && calc.model == "20B" => "financial"
case _ if calc.brand == "HP" && calc.model == "48G" => "scientific"
case _ if calc.brand == "HP" && calc.model == "30B" => "business"
case _ => "unknown"
}
OK,写起来有点繁琐。我们用case class来改造它。
创建case class Calculator
case class Calculator(brand: String, model: String)
然后模式匹配就可以精简成如下代码块:
def calcType(calc: Calculator) = calc match {
case Calculator("HP", "20B") => "financial"
case Calculator("HP", "48G") => "scientific"
case Calculator("HP", "30B") => "business"
case case _ => "Calculator of unknown type"
}