样例类仍然是类。
样例类用case关键字进行声明。
样例类是为模式匹配而优化的类。
构造器中的每一个参数都成为val-除非它被显式地声明为var(不建议这样做)。
在样例类对应的伴生对象中提供apply方法,不用new关键字就能构造出相应的对象。
提供unapply方法让模式匹配可以工作。
自动生成toString、equals、hashCode和copy方法(有点类似模版类,直接给生成,供程序员使用)。
除上述外,样例类和其它类完全一样。可以添加字段和方法,扩展它们。
object CaseClassDemo01 {
def main(args: Array[String]): Unit = {
println("hello~~")
}
}
abstract class Amount
case class Dollar(value: Double) extends Amount //样例类
case class Currency(value: Double, unit: String) extends Amount //样例类
case object NoAmount extends Amount //样例类
object boke_demo01 {
def main(args: Array[String]): Unit = {
//该案例的作用就是体验使用样例类方式进行对象匹配简洁性
for (amt <- Array(Dollar(1000.0), Currency(1000.0, "RMB"), NoAmount)) {
val result = amt match {
//说明
case Dollar(v) => "$" + v // $1000.0
//说明
case Currency(v, u) => v + " " + u // 1000.0 RMB
case NoAmount => "NoAmount" // NoAmount
}
println(amt + ": " + result)
}
}
}
abstract class Amount
case class Dollar(value: Double) extends Amount //样例类
case class Currency(value: Double, unit: String) extends Amount //样例类
case object NoAmount extends Amount //样例类
object boke_demo01 {
def main(args: Array[String]): Unit = {
val amt = new Currency(3000.0, "RMB")
val amt2 = amt.copy() // 克隆,创建的对象和amt的属性一样
println("amt2.value" + amt2.value + " amt2.unit= " + amt2.unit)
println(amt2)
val amt3 = amt.copy(value = 8000.0)
println(amt3)
val amt4 = amt.copy(unit = "美元")
println(amt4)
}
}
abstract class Amount
case class Dollar(value: Double) extends Amount //样例类
case class Currency(value: Double, unit: String) extends Amount //样例类
case object NoAmount extends Amount //样例类
scala> :paste
// Entering paste mode (ctrl-D to finish)
List(1, 3, 5, 9) match { //修改并测试
//1.两个元素间::叫中置表达式,至少first,second两个匹配才行.
//2.first 匹配第一个 second 匹配第二个, rest 匹配剩余部分(5,9)
case first :: second :: rest => println(first + " " + second + " " + rest.length + " " + rest) //
case _ => println("匹配不到...")
}
// Exiting paste mode, now interpreting.
case first :: second :: rest => println(first + " " + second + " " + rest.length + " " + rest) //
^
<pastie>:4: warning: method + in class Int is deprecated (since 2.13.0): Adding a number and a String is deprecated. Use the string interpolation `s"$num$str"`
1 3 2 List(5, 9)
scala>
————Blueicex 2020/2/16 20:17 blueice1980@126.com