使用样本类可以方便得存储和匹配类的内容。你不用new关键字就可以创建它们。
scala> case class Calculator(brand: String, model: String)
defined class Calculator
scala> val hp20b = Calculator("hp", "20b")
hp20b: Calculator = Calculator(hp,20b)
样本类基于构造函数的参数,自动地实现了相等性和易读的toString方法。
scala> val hp20b = Calculator("hp", "20b")
hp20b: Calculator = Calculator(hp,20b)
scala> val hp20B = Calculator("hp", "20b")
hp20B: Calculator = Calculator(hp,20b)
scala> hp20b == hp20B
res6: Boolean = true
样本类也可以像普通类那样拥有方法。
使用样本类进行模式匹配 case classes are designed to be used with pattern matching. Let’s simplify our calculator classifier example from earlier. 样本类就是被设计用在模式匹配中的。让我们简化之前的计算器分类器的例子。
val hp20b = Calculator("hp", "20B")
val hp30b = Calculator("hp", "30B")
def calcType(calc: Calculator) = calc match {
case Calculator("hp", "20B") => "financial"
case Calculator("hp", "48G") => "scientific"
case Calculator("hp", "30B") => "business"
case Calculator(ourBrand, ourModel) => "Calculator: %s %s is of unknown type".format(ourBrand, ourModel)
}
最后一句也可以这样写
case Calculator(_, _) => "Calculator of unknown type"
或者我们完全可以不将匹配对象指定为Calculator类型
case _ => "Calculator of unknown type"
或者我们也可以将匹配的值重新命名。
在我们项目实际使用中将实体类定义为样本类,例如:
case c@Calculator(_, _) => "Calculator: %s of unknown type".format(c)
case class Student(name : String,age:int)
case 还有一些别的用法:
scala> case class PhoneExt(name: String, ext: Int)
defined class PhoneExt
scala> val extensions = List(PhoneExt("steve", 100), PhoneExt("robey", 200))
extensions: List[PhoneExt] = List(PhoneExt(steve,100), PhoneExt(robey,200))
scala> extensions.filter { case PhoneExt(name, extension) => extension < 200 }
res0: List[PhoneExt] = List(PhoneExt(steve,100))
为什么这段代码可以工作?
filter使用一个函数。在这个例子中是一个谓词函数(PhoneExt) => Boolean
。
PartialFunction是Function的子类型,所以filter也可以使用PartialFunction!